Untitled
  1. package com.aspose.pdf.examples.workingwithdocuments;
  2.  
  3. import com.aspose.pdf.Document;
  4. import com.aspose.pdf.Page;
  5. import com.aspose.pdf.TextFragment;
  6. import com.aspose.pdf.devices.PngDevice;
  7. import com.aspose.pdf.devices.Resolution;
  8. import com.aspose.pdf.examples.ExampleConfig;
  9. import com.aspose.pdf.examples.ExampleDataDirs;
  10. import com.aspose.pdf.examples.ExampleRunner;
  11.  
  12. import javax.imageio.ImageIO;
  13. import java.io.File;
  14. import java.io.FileNotFoundException;
  15. import java.io.IOException;
  16. import java.nio.file.Files;
  17. import java.nio.file.Path;
  18. import java.util.Scanner;
  19. import java.util.concurrent.TimeUnit;
  20.  
  21. public final class CreatePdfDocumentExamples {
  22. // Change this to match your installation, or use "tesseract" for PATH lookup.
  23. private static final String TESSERACT_PATH = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe";
  24. private static final long TESSERACT_TIMEOUT_MINUTES = 2;
  25.  
  26. private CreatePdfDocumentExamples() {
  27. }
  28.  
  29. public static void createNewDocument(Path outputFile) {
  30. try (Document document = new Document()) {
  31. Page page = document.getPages().add();
  32. page.getParagraphs().add(new TextFragment("Hello World!"));
  33. document.save(outputFile.toString());
  34. }
  35. }
  36.  
  37. // Begin examples Searchable PDF
  38. public static void createSearchablePdf_1(Path inputFile, Path outputFile) {
  39. Path tempDir = outputFile.toAbsolutePath().getParent().resolve("ocr-temp");
  40.  
  41. // Create callBack - logic recognize text for PDF images. Use outer OCR supports
  42. // HOCR standard(en.wikipedia.org
  43. // We have used free google tesseract
  44.  
  45. Document.CallBackGetHocr callBackGetHocr = new Document.CallBackGetHocr() {
  46. @Override
  47. public String invoke(java.awt.image.BufferedImage img) {
  48. File outputfile = tempDir.resolve("test.jpg").toFile();
  49. try {
  50. Files.createDirectories(tempDir);
  51. ImageIO.write(img, "jpg", outputfile);
  52. } catch (IOException e1) {
  53. throw new java.io.UncheckedIOException("Failed to write OCR image.", e1);
  54. }
  55.  
  56. try {
  57. Path outputBase = tempDir.resolve("out");
  58. runTesseract(outputfile.toPath(), outputBase, "hocr", tempDir.resolve("tesseract.log"));
  59. } catch (IOException e) {
  60. throw new java.io.UncheckedIOException("Tesseract OCR failed.", e);
  61. } catch (InterruptedException e) {
  62. Thread.currentThread().interrupt();
  63. throw new IllegalStateException("Tesseract OCR was interrupted.", e);
  64. }
  65.  
  66. // reading out.html to string
  67. File file = tempDir.resolve("out.hocr").toFile();
  68. StringBuilder fileContents = new StringBuilder((int) file.length());
  69. Scanner scanner = null;
  70. try {
  71. scanner = new Scanner(file);
  72. String lineSeparator = System.getProperty("line.separator");
  73.  
  74. while (scanner.hasNextLine()) {
  75. fileContents.append(scanner.nextLine() + lineSeparator);
  76. }
  77. } catch (FileNotFoundException e) {
  78. throw new java.io.UncheckedIOException("Tesseract OCR failed.", e);
  79. } finally {
  80. if (scanner != null)
  81. scanner.close();
  82. }
  83.  
  84. // deleting temp files
  85. File fileOut = tempDir.resolve("out.hocr").toFile();
  86. if (fileOut.exists()) {
  87. fileOut.delete();
  88. }
  89. File fileLog = tempDir.resolve("tesseract.log").toFile();
  90. if (fileLog.exists()) {
  91. fileLog.delete();
  92. }
  93. File fileTest = tempDir.resolve("test.jpg").toFile();
  94. if (fileTest.exists()) {
  95. fileTest.delete();
  96. }
  97.  
  98. return fileContents.toString();
  99. }
  100. };
  101. // End callBack
  102. try (Document document = new Document(inputFile.toString())) {
  103. if (!document.convert(callBackGetHocr))
  104. throw new RuntimeException("Failed to convert document.");
  105. document.save(outputFile.toString());
  106. }
  107. }
  108.  
  109. /**
  110. * Creates a searchable PDF using Tesseract 4 or newer with English LSTM data.
  111. */
  112. public static void createSearchablePdf_2(Path inputFile, Path outputFile)
  113. throws IOException, InterruptedException {
  114. Path outputDirectory = outputFile.toAbsolutePath().getParent();
  115. Files.createDirectories(outputDirectory);
  116. Path tempDir = Files.createTempDirectory(outputDirectory, "ocr-");
  117. Path tempImage = tempDir.resolve("page.png");
  118. Path tempDoc = tempDir.resolve("page");
  119. Path tempPdf = tempDir.resolve("page.pdf");
  120. Path tempLog = tempDir.resolve("page.log");
  121. Throwable failure = null;
  122. try (Document inputDocument = new Document(inputFile.toString());
  123. Document outputDocument = new Document()) {
  124. PngDevice pngDevice = new PngDevice(new Resolution(600));
  125. for (Page page : inputDocument.getPages()) {
  126. pngDevice.process(page, tempImage.toString());
  127. runTesseract(tempImage, tempDoc, "pdf", tempLog);
  128. outputDocument.merge(tempPdf.toString());
  129. Files.deleteIfExists(tempPdf);
  130. }
  131. outputDocument.save(outputFile.toString());
  132. } catch (InterruptedException e) {
  133. failure = e;
  134. Thread.currentThread().interrupt();
  135. throw e;
  136. } catch (IOException | RuntimeException | Error e) {
  137. failure = e;
  138. throw e;
  139. } finally {
  140. IOException cleanupFailure = null;
  141. for (Path path : new Path[]{tempImage, tempPdf, tempLog, tempDir}) {
  142. try {
  143. Files.deleteIfExists(path);
  144. } catch (IOException e) {
  145. if (cleanupFailure == null) {
  146. cleanupFailure = e;
  147. } else {
  148. cleanupFailure.addSuppressed(e);
  149. }
  150. }
  151. }
  152. if (cleanupFailure != null) {
  153. if (failure != null) {
  154. failure.addSuppressed(cleanupFailure);
  155. } else {
  156. throw cleanupFailure;
  157. }
  158. }
  159. }
  160. }
  161.  
  162.  
  163. private static void runTesseract(Path image, Path outputBase, String format, Path log)
  164. throws IOException, InterruptedException {
  165. Path result = Path.of(outputBase + "." + format);
  166. Files.deleteIfExists(result);
  167. ProcessBuilder builder = new ProcessBuilder(
  168. TESSERACT_PATH, image.toString(), outputBase.toString(),
  169. "-l", "eng", "--oem", "1", "--psm", "3", format);
  170. builder.redirectErrorStream(true);
  171. builder.redirectOutput(log.toFile());
  172. Process process = builder.start();
  173. try {
  174. process.getOutputStream().close();
  175. if (!process.waitFor(TESSERACT_TIMEOUT_MINUTES, TimeUnit.MINUTES)) {
  176. throw new IOException("Tesseract timed out after "
  177. + TESSERACT_TIMEOUT_MINUTES + " minutes while processing " + image);
  178. }
  179. if (process.exitValue() != 0 || !Files.isRegularFile(result)
  180. || Files.size(result) == 0) {
  181. throw new IOException("Tesseract failed (exit " + process.exitValue()
  182. + ") while processing " + image + ": " + Files.readString(log));
  183. }
  184. } finally {
  185. if (process.isAlive()) {
  186. process.destroyForcibly();
  187. process.onExit().join();
  188. }
  189. }
  190. }
  191.  
  192. // End examples Searchable PDF
  193. public static void runAllExamples(String licensePath) throws Exception {
  194. ExampleConfig.setLicense(licensePath);
  195. ExampleDataDirs dirs = ExampleConfig.initializeDataDir("working_with_documents");
  196.  
  197. ExampleRunner.run("Create new document",
  198. () -> createNewDocument(dirs.outputFile("create_new_document.pdf")));
  199. ExampleRunner.run("Create searchable PDF (Method 1)",
  200. () -> createSearchablePdf_1(
  201. dirs.inputFile("sample5.pdf"),
  202. dirs.outputFile("create_searchable_pdf_1.pdf")));
  203. ExampleRunner.run("Create searchable PDF (Method 2)",
  204. () -> createSearchablePdf_2(
  205. dirs.inputFile("sample5.pdf"),
  206. dirs.outputFile("create_searchable_pdf_2.pdf")));
  207.  
  208. System.out.println();
  209. System.out.println("All PDF creation examples finished.");
  210. }
  211.  
  212. public static void main(String[] args) throws Exception {
  213. runAllExamples(ExampleConfig.resolveLicensePath(args));
  214. }
  215. }
  216.  
Pasted 2026-10-28 02:19:32

Short link: