Sample code for 30+ languages & platforms
Java Requires Chilkat v11.7.0+

Extract PDF Text to a StringBuilder and Save to a File

See more PDF Text Extraction Examples

Demonstrates ExtractTextSb, which writes the extracted text to a StringBuilder instead of returning it as a JSON string. Use it for large documents. The JSON output still receives the quality report.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Pdf;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // The PDF used in this example is available at long_report.pdf

        Pdf pdf = new Pdf();
        try {
            pdf.loadFile("qa_data/pdf/long_report.pdf");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Number of pages: " + pdf.getNumPages());

        // ExtractTextSb takes the same operation and options as ExtractText, but the text
        // goes to a StringBuilder.  This avoids building a very large JSON string for
        // documents with many pages.
        JsonObject json = new JsonObject();
        StringBuilder sbText = new StringBuilder();
        JsonObject jsonOut = new JsonObject();

        try {
            pdf.extractTextSb("text", json, sbText, jsonOut);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Extracted " + sbText.getLength() + " characters.");

        // Save the text to a file.
        try {
            sbText.writeFile("qa_output/long_report.txt", "utf-8", false);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // The JSON output does not contain the text, but it still has the quality report.
        System.out.println("Quality: " + jsonOut.stringOf("quality.rating"));
        System.out.println("Pages with no text (need OCR): [" + jsonOut.stringOf("quality.pagesNeedingOcr") + "]");

        // Sample output:

        // Number of pages: 3
        // Extracted 4522 characters.
        // Quality: good
        // Pages with no text (need OCR): []
    }
}