Java Requires Chilkat v11.7.0+
Chilkat2 Java
Extract One Section of a PDF by its Heading
See more PDF Text Extraction Examples
Demonstrates "labelValue": "section", which returns everything from a heading up to the next heading of the same or higher level. With the "markdown" operation the section keeps its own sub-headings.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Pdf;
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 sectioned_doc.pdf
Pdf pdf = new Pdf();
try {
pdf.loadFile("qa_data/pdf/sectioned_doc.pdf");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
JsonObject json = new JsonObject();
JsonObject jsonOut = new JsonObject();
// The document has the sections Introduction, Opening Hours, Terms and Conditions (with the
// sub-sections Admission, Safety and Liability) and Contact. Get the Terms and Conditions:
// everything after that heading up to the next heading of the same level (Contact). The heading
// itself is not part of the value; labelMatches[0].label has it.
json.updateString("label", "Terms and Conditions");
json.updateString("labelValue", "section");
try {
pdf.extractText("markdown", json, jsonOut);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println(jsonOut.stringOf("markdown"));
// The same with the "text" operation gives the section as plain text.
try {
pdf.extractText("text", json, jsonOut);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("---- as text ----");
System.out.println(jsonOut.stringOf("text"));
// Sample output:
// ### Admission
//
// Admission is free. Groups of more than ten should book in advance so that a volunteer can be assigned to them.
//
// ### Safety
//
// No more than eight people may be on the stair at one time. Children under twelve must be accompanied by an adult, and the lantern room is closed in high winds.
//
// ### Liability
//
// Visitors climb the tower at their own risk. The society carries public liability insurance but accepts no responsibility for personal property.
// ---- as text ----
// Admission
//
// Admission is free. Groups of more than ten should book in advance so that a volunteer can be assigned to them.
//
// Safety
//
// No more than eight people may be on the stair at one time. Children under twelve must be accompanied by an adult, and the lantern room is closed in high winds.
//
// Liability
//
// Visitors climb the tower at their own risk. The society carries public liability insurance but accepts no responsibility for personal property.
}
}