andruhovski

Untitled

Oct 28th, 2026
165
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.20 KB | None | 0 0
  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(http://en.wikipedia.org/wiki/HOCR).
  43. // We have used free google tesseract
  44. // OCR(http://en.wikipedia.org/wiki/Tesseract_%28software%29)
  45.  
  46. Document.CallBackGetHocr callBackGetHocr = new Document.CallBackGetHocr() {
  47. @Override
  48. public String invoke(java.awt.image.BufferedImage img) {
  49. File outputfile = tempDir.resolve("test.jpg").toFile();
  50. try {
  51. Files.createDirectories(tempDir);
  52. ImageIO.write(img, "jpg", outputfile);
  53. } catch (IOException e1) {
  54. throw new java.io.UncheckedIOException("Failed to write OCR image.", e1);
  55. }
  56.  
  57. try {
  58. Path outputBase = tempDir.resolve("out");
  59. runTesseract(outputfile.toPath(), outputBase, "hocr", tempDir.resolve("tesseract.log"));
  60. } catch (IOException e) {
  61. throw new java.io.UncheckedIOException("Tesseract OCR failed.", e);
  62. } catch (InterruptedException e) {
  63. Thread.currentThread().interrupt();
  64. throw new IllegalStateException("Tesseract OCR was interrupted.", e);
  65. }
  66.  
  67. // reading out.html to string
  68. File file = tempDir.resolve("out.hocr").toFile();
  69. StringBuilder fileContents = new StringBuilder((int) file.length());
  70. Scanner scanner = null;
  71. try {
  72. scanner = new Scanner(file);
  73. String lineSeparator = System.getProperty("line.separator");
  74.  
  75. while (scanner.hasNextLine()) {
  76. fileContents.append(scanner.nextLine() + lineSeparator);
  77. }
  78. } catch (FileNotFoundException e) {
  79. throw new java.io.UncheckedIOException("Tesseract OCR failed.", e);
  80. } finally {
  81. if (scanner != null)
  82. scanner.close();
  83. }
  84.  
  85. // deleting temp files
  86. File fileOut = tempDir.resolve("out.hocr").toFile();
  87. if (fileOut.exists()) {
  88. fileOut.delete();
  89. }
  90. File fileLog = tempDir.resolve("tesseract.log").toFile();
  91. if (fileLog.exists()) {
  92. fileLog.delete();
  93. }
  94. File fileTest = tempDir.resolve("test.jpg").toFile();
  95. if (fileTest.exists()) {
  96. fileTest.delete();
  97. }
  98.  
  99. return fileContents.toString();
  100. }
  101. };
  102. // End callBack
  103. try (Document document = new Document(inputFile.toString())) {
  104. if (!document.convert(callBackGetHocr))
  105. throw new RuntimeException("Failed to convert document.");
  106. document.save(outputFile.toString());
  107. }
  108. }
  109.  
  110. /**
  111. * Creates a searchable PDF using Tesseract 4 or newer with English LSTM data.
  112. */
  113. public static void createSearchablePdf_2(Path inputFile, Path outputFile)
  114. throws IOException, InterruptedException {
  115. Path outputDirectory = outputFile.toAbsolutePath().getParent();
  116. Files.createDirectories(outputDirectory);
  117. Path tempDir = Files.createTempDirectory(outputDirectory, "ocr-");
  118. Path tempImage = tempDir.resolve("page.png");
  119. Path tempDoc = tempDir.resolve("page");
  120. Path tempPdf = tempDir.resolve("page.pdf");
  121. Path tempLog = tempDir.resolve("page.log");
  122. Throwable failure = null;
  123. try (Document inputDocument = new Document(inputFile.toString());
  124. Document outputDocument = new Document()) {
  125. PngDevice pngDevice = new PngDevice(new Resolution(600));
  126. for (Page page : inputDocument.getPages()) {
  127. pngDevice.process(page, tempImage.toString());
  128. runTesseract(tempImage, tempDoc, "pdf", tempLog);
  129. outputDocument.merge(tempPdf.toString());
  130. Files.deleteIfExists(tempPdf);
  131. }
  132. outputDocument.save(outputFile.toString());
  133. } catch (InterruptedException e) {
  134. failure = e;
  135. Thread.currentThread().interrupt();
  136. throw e;
  137. } catch (IOException | RuntimeException | Error e) {
  138. failure = e;
  139. throw e;
  140. } finally {
  141. IOException cleanupFailure = null;
  142. for (Path path : new Path[]{tempImage, tempPdf, tempLog, tempDir}) {
  143. try {
  144. Files.deleteIfExists(path);
  145. } catch (IOException e) {
  146. if (cleanupFailure == null) {
  147. cleanupFailure = e;
  148. } else {
  149. cleanupFailure.addSuppressed(e);
  150. }
  151. }
  152. }
  153. if (cleanupFailure != null) {
  154. if (failure != null) {
  155. failure.addSuppressed(cleanupFailure);
  156. } else {
  157. throw cleanupFailure;
  158. }
  159. }
  160. }
  161. }
  162.  
  163.  
  164. private static void runTesseract(Path image, Path outputBase, String format, Path log)
  165. throws IOException, InterruptedException {
  166. Path result = Path.of(outputBase + "." + format);
  167. Files.deleteIfExists(result);
  168. ProcessBuilder builder = new ProcessBuilder(
  169. TESSERACT_PATH, image.toString(), outputBase.toString(),
  170. "-l", "eng", "--oem", "1", "--psm", "3", format);
  171. builder.redirectErrorStream(true);
  172. builder.redirectOutput(log.toFile());
  173. Process process = builder.start();
  174. try {
  175. process.getOutputStream().close();
  176. if (!process.waitFor(TESSERACT_TIMEOUT_MINUTES, TimeUnit.MINUTES)) {
  177. throw new IOException("Tesseract timed out after "
  178. + TESSERACT_TIMEOUT_MINUTES + " minutes while processing " + image);
  179. }
  180. if (process.exitValue() != 0 || !Files.isRegularFile(result)
  181. || Files.size(result) == 0) {
  182. throw new IOException("Tesseract failed (exit " + process.exitValue()
  183. + ") while processing " + image + ": " + Files.readString(log));
  184. }
  185. } finally {
  186. if (process.isAlive()) {
  187. process.destroyForcibly();
  188. process.onExit().join();
  189. }
  190. }
  191. }
  192.  
  193. // End examples Searchable PDF
  194. public static void runAllExamples(String licensePath) throws Exception {
  195. ExampleConfig.setLicense(licensePath);
  196. ExampleDataDirs dirs = ExampleConfig.initializeDataDir("working_with_documents");
  197.  
  198. ExampleRunner.run("Create new document",
  199. () -> createNewDocument(dirs.outputFile("create_new_document.pdf")));
  200. ExampleRunner.run("Create searchable PDF (Method 1)",
  201. () -> createSearchablePdf_1(
  202. dirs.inputFile("sample5.pdf"),
  203. dirs.outputFile("create_searchable_pdf_1.pdf")));
  204. ExampleRunner.run("Create searchable PDF (Method 2)",
  205. () -> createSearchablePdf_2(
  206. dirs.inputFile("sample5.pdf"),
  207. dirs.outputFile("create_searchable_pdf_2.pdf")));
  208.  
  209. System.out.println();
  210. System.out.println("All PDF creation examples finished.");
  211. }
  212.  
  213. public static void main(String[] args) throws Exception {
  214. runAllExamples(ExampleConfig.resolveLicensePath(args));
  215. }
  216. }
  217.  
Advertisement