Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.aspose.pdf.examples.workingwithdocuments;
- import com.aspose.pdf.Document;
- import com.aspose.pdf.Page;
- import com.aspose.pdf.TextFragment;
- import com.aspose.pdf.devices.PngDevice;
- import com.aspose.pdf.devices.Resolution;
- import com.aspose.pdf.examples.ExampleConfig;
- import com.aspose.pdf.examples.ExampleDataDirs;
- import com.aspose.pdf.examples.ExampleRunner;
- import javax.imageio.ImageIO;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.util.Scanner;
- import java.util.concurrent.TimeUnit;
- public final class CreatePdfDocumentExamples {
- // Change this to match your installation, or use "tesseract" for PATH lookup.
- private static final String TESSERACT_PATH = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe";
- private static final long TESSERACT_TIMEOUT_MINUTES = 2;
- private CreatePdfDocumentExamples() {
- }
- public static void createNewDocument(Path outputFile) {
- try (Document document = new Document()) {
- Page page = document.getPages().add();
- page.getParagraphs().add(new TextFragment("Hello World!"));
- document.save(outputFile.toString());
- }
- }
- // Begin examples Searchable PDF
- public static void createSearchablePdf_1(Path inputFile, Path outputFile) {
- Path tempDir = outputFile.toAbsolutePath().getParent().resolve("ocr-temp");
- // Create callBack - logic recognize text for PDF images. Use outer OCR supports
- // HOCR standard(http://en.wikipedia.org/wiki/HOCR).
- // We have used free google tesseract
- // OCR(http://en.wikipedia.org/wiki/Tesseract_%28software%29)
- Document.CallBackGetHocr callBackGetHocr = new Document.CallBackGetHocr() {
- @Override
- public String invoke(java.awt.image.BufferedImage img) {
- File outputfile = tempDir.resolve("test.jpg").toFile();
- try {
- Files.createDirectories(tempDir);
- ImageIO.write(img, "jpg", outputfile);
- } catch (IOException e1) {
- throw new java.io.UncheckedIOException("Failed to write OCR image.", e1);
- }
- try {
- Path outputBase = tempDir.resolve("out");
- runTesseract(outputfile.toPath(), outputBase, "hocr", tempDir.resolve("tesseract.log"));
- } catch (IOException e) {
- throw new java.io.UncheckedIOException("Tesseract OCR failed.", e);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new IllegalStateException("Tesseract OCR was interrupted.", e);
- }
- // reading out.html to string
- File file = tempDir.resolve("out.hocr").toFile();
- StringBuilder fileContents = new StringBuilder((int) file.length());
- Scanner scanner = null;
- try {
- scanner = new Scanner(file);
- String lineSeparator = System.getProperty("line.separator");
- while (scanner.hasNextLine()) {
- fileContents.append(scanner.nextLine() + lineSeparator);
- }
- } catch (FileNotFoundException e) {
- throw new java.io.UncheckedIOException("Tesseract OCR failed.", e);
- } finally {
- if (scanner != null)
- scanner.close();
- }
- // deleting temp files
- File fileOut = tempDir.resolve("out.hocr").toFile();
- if (fileOut.exists()) {
- fileOut.delete();
- }
- File fileLog = tempDir.resolve("tesseract.log").toFile();
- if (fileLog.exists()) {
- fileLog.delete();
- }
- File fileTest = tempDir.resolve("test.jpg").toFile();
- if (fileTest.exists()) {
- fileTest.delete();
- }
- return fileContents.toString();
- }
- };
- // End callBack
- try (Document document = new Document(inputFile.toString())) {
- if (!document.convert(callBackGetHocr))
- throw new RuntimeException("Failed to convert document.");
- document.save(outputFile.toString());
- }
- }
- /**
- * Creates a searchable PDF using Tesseract 4 or newer with English LSTM data.
- */
- public static void createSearchablePdf_2(Path inputFile, Path outputFile)
- throws IOException, InterruptedException {
- Path outputDirectory = outputFile.toAbsolutePath().getParent();
- Files.createDirectories(outputDirectory);
- Path tempDir = Files.createTempDirectory(outputDirectory, "ocr-");
- Path tempImage = tempDir.resolve("page.png");
- Path tempDoc = tempDir.resolve("page");
- Path tempPdf = tempDir.resolve("page.pdf");
- Path tempLog = tempDir.resolve("page.log");
- Throwable failure = null;
- try (Document inputDocument = new Document(inputFile.toString());
- Document outputDocument = new Document()) {
- PngDevice pngDevice = new PngDevice(new Resolution(600));
- for (Page page : inputDocument.getPages()) {
- pngDevice.process(page, tempImage.toString());
- runTesseract(tempImage, tempDoc, "pdf", tempLog);
- outputDocument.merge(tempPdf.toString());
- Files.deleteIfExists(tempPdf);
- }
- outputDocument.save(outputFile.toString());
- } catch (InterruptedException e) {
- failure = e;
- Thread.currentThread().interrupt();
- throw e;
- } catch (IOException | RuntimeException | Error e) {
- failure = e;
- throw e;
- } finally {
- IOException cleanupFailure = null;
- for (Path path : new Path[]{tempImage, tempPdf, tempLog, tempDir}) {
- try {
- Files.deleteIfExists(path);
- } catch (IOException e) {
- if (cleanupFailure == null) {
- cleanupFailure = e;
- } else {
- cleanupFailure.addSuppressed(e);
- }
- }
- }
- if (cleanupFailure != null) {
- if (failure != null) {
- failure.addSuppressed(cleanupFailure);
- } else {
- throw cleanupFailure;
- }
- }
- }
- }
- private static void runTesseract(Path image, Path outputBase, String format, Path log)
- throws IOException, InterruptedException {
- Path result = Path.of(outputBase + "." + format);
- Files.deleteIfExists(result);
- ProcessBuilder builder = new ProcessBuilder(
- TESSERACT_PATH, image.toString(), outputBase.toString(),
- "-l", "eng", "--oem", "1", "--psm", "3", format);
- builder.redirectErrorStream(true);
- builder.redirectOutput(log.toFile());
- Process process = builder.start();
- try {
- process.getOutputStream().close();
- if (!process.waitFor(TESSERACT_TIMEOUT_MINUTES, TimeUnit.MINUTES)) {
- throw new IOException("Tesseract timed out after "
- + TESSERACT_TIMEOUT_MINUTES + " minutes while processing " + image);
- }
- if (process.exitValue() != 0 || !Files.isRegularFile(result)
- || Files.size(result) == 0) {
- throw new IOException("Tesseract failed (exit " + process.exitValue()
- + ") while processing " + image + ": " + Files.readString(log));
- }
- } finally {
- if (process.isAlive()) {
- process.destroyForcibly();
- process.onExit().join();
- }
- }
- }
- // End examples Searchable PDF
- public static void runAllExamples(String licensePath) throws Exception {
- ExampleConfig.setLicense(licensePath);
- ExampleDataDirs dirs = ExampleConfig.initializeDataDir("working_with_documents");
- ExampleRunner.run("Create new document",
- () -> createNewDocument(dirs.outputFile("create_new_document.pdf")));
- ExampleRunner.run("Create searchable PDF (Method 1)",
- () -> createSearchablePdf_1(
- dirs.inputFile("sample5.pdf"),
- dirs.outputFile("create_searchable_pdf_1.pdf")));
- ExampleRunner.run("Create searchable PDF (Method 2)",
- () -> createSearchablePdf_2(
- dirs.inputFile("sample5.pdf"),
- dirs.outputFile("create_searchable_pdf_2.pdf")));
- System.out.println();
- System.out.println("All PDF creation examples finished.");
- }
- public static void main(String[] args) throws Exception {
- runAllExamples(ExampleConfig.resolveLicensePath(args));
- }
- }
Advertisement