Convert HTML to Plain Text With jsoup
Practical steps for using jsoup to convert HTML into plain text in a local Java or Kotlin project, including output checks and common fixes.
Before you start
This is a local conversion task for a Java or Kotlin project. You do not need an online service or an API key. Add the jsoup library to your project and prepare either an HTML string, a file you can read, or a remote page that your code is permitted to fetch.
Step-by-step instructions
First, parse the HTML with Jsoup.parse. For an HTML string, pass the string directly to Jsoup.parse. For a file, read the content with a supported method such as Jsoup.parse(File, charsetName). For a URL, use Jsoup.connect(url).get() only when fetching is allowed by your application and the target permits it.
Next, call the text method on the returned Document. For example, after Document doc = Jsoup.parse(html), use doc.text() to get a stripped plain text version. The text method removes markup and combines remaining text with a single space between elements where needed.
If you need more control, use doc.body().text() to skip content outside the body. You can also select a narrower area first, such as doc.select first, then call text on the resulting elements. Keep the parsed Document if you may reuse it later; the conversion does not change the original source string.
Check the output
Print or return the resulting string and compare it with a known small HTML sample. Script and style content may be excluded or included depending on the jsoup version and how it processes those elements, so verify the version behavior with your sample rather than assuming every tag is removed.
Common problems and next steps
If output appears as one long run without line breaks, that is expected: text returns a plain string, not a formatted layout. Add explicit newline handling in your own code when you need a line-based representation.
If whitespace is irregular, normalize the result with replaceAll or trim as appropriate for your use. For entities such as a non-breaking space, compare the result against the input encoding rather than guessing before normalization.
If remote content fails to load, check the connection timeout, user agent and error status in your code. Fetching depends on network access and target response, so isolate the fetch from the text conversion when diagnosing. Store the parsed Document in memory only for the current operation unless your application needs to retain it.