List of usage examples for org.apache.pdfbox.rendering PDFRenderer PDFRenderer
public PDFRenderer(PDDocument document)
From source file:pdf.WriteOffProductsPDF.java
public void createWriteOffProductsPNG(String path) throws IOException { File file = new File(path); PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); BufferedImage image = renderer.renderImage(0); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy."); ImageIO.write(image, "PNG", new File( "pdf_docs\\write_off_products_picture\\" + "woppic-" + sdf.format(dateOfWriteOff) + ".png")); doc.close();// w w w . ja v a2s .c o m }
From source file:pdfsplicer.SplicerModel.java
License:Open Source License
/** * Render an image for the first page of the selected loaded PDF. * /* w w w .j a va2 s . c om*/ * @param selectedValue the name of the selected PDF * @throws IOException if the selected PDF cannot be read */ public void showLoadedPDFPreview(String selectedValue) throws IOException { lPDFIcon = null; curLPage = -1; lNumPages = -1; if (selectedValue != null) { PDDocument pdf = pdfList.get(selectedValue); loadedRenderer = new PDFRenderer(pdf); lPDFIcon = new ImageIcon(loadedRenderer.renderImage(0)); curLPage = 1; lNumPages = pdf.getNumberOfPages(); } setChanged(); notifyObservers(); }
From source file:pdfsplicer.SplicerModel.java
License:Open Source License
/** * Render an image for the first page of the finalized PDF. * //w ww . ja va 2 s . c om * @throws IOException if the loaded PDF from where the page came from cannot be read */ public void showFinalPDFPreview() throws IOException { fPDFIcon = null; curFPage = -1; if (numPageRanges > 0) { PDDocument pdf = pdfList.get(pageEntryPDFList.get(0)); finalRenderer = new PDFRenderer(pdf); fPDFIcon = new ImageIcon(finalRenderer.renderImage(0)); curFPage = 1; } setChanged(); notifyObservers(); }
From source file:pdfsplicer.SplicerModel.java
License:Open Source License
/** * Render an image for the selected page of the finalized PDF. * //from w w w .j a v a 2s .c o m * @param pageNum the number of the selected page to be rendered * @throws IOException if the loaded PDF from where the page came from cannot be read */ public void changeFinalPDFPreviewPage(int pageNum) throws IOException { if (pageNum < 1) { pageNum = 1; } else if (pageNum > fNumPages) { pageNum = fNumPages; } fPDFIcon = null; int cPage = 1; int rangeNum = 0; int nextSize = pageRangeList.get(rangeNum).size(); ; while (cPage + nextSize <= pageNum) { cPage += nextSize; if (rangeNum + 1 < numPageRanges) { nextSize = pageRangeList.get(++rangeNum).size(); } } PDDocument pdf = pdfList.get(pageEntryPDFList.get(rangeNum)); int pageNumPos = pageRangeList.get(rangeNum).get(pageNum - cPage); finalRenderer = new PDFRenderer(pdf); fPDFIcon = new ImageIcon(finalRenderer.renderImage(pageNumPos - 1)); curFPage = pageNum; setChanged(); notifyObservers(); }
From source file:pdfthumbnailgenerator.PDFThumbnailGenerator.java
/** * @param args the command line arguments *//*w w w . java 2 s. co m*/ public static void main(String[] args) { if (args.length < 3) { System.out.println("Usage: pdfPath jpegOutputPath"); System.exit(-1); } File file = new File(args[1]); try { try (PDDocument document = PDDocument.load(file)) { PDFRenderer renderer = new PDFRenderer(document); BufferedImage image = renderer.renderImage(0); ImageIO.write(image, "JPEG", new File(args[2])); document.close(); System.exit(0); } } catch (Exception ex) { System.exit(-1); } }
From source file:richtercloud.document.scanner.gui.Tools.java
License:Open Source License
/** * Uses a modal dialog in order to display the progress of the retrieval and * make the operation cancelable./*from w ww .jav a 2 s. co m*/ * @param documentFile * @return the retrieved images or {@code null} if the retrieval has been * canceled (in dialog) * @throws DocumentAddException * @throws InterruptedException * @throws ExecutionException */ /* internal implementation notes: - can't use ProgressMonitor without blocking EVT instead of a model dialog when using SwingWorker.get */ public static List<ImageWrapper> retrieveImages(final File documentFile, Window waitDialogParent, File imageWrapperStorageDir, IssueHandler issueHandler) throws DocumentAddException, InterruptedException, ExecutionException { if (documentFile == null) { throw new IllegalArgumentException("documentFile mustn't be null"); } final SwingWorkerGetWaitDialog dialog = new SwingWorkerGetWaitDialog( SwingUtilities.getWindowAncestor(waitDialogParent), //owner DocumentScanner.generateApplicationWindowTitle("Wait", Constants.APP_NAME, Constants.APP_VERSION), //dialogTitle "Retrieving image data", //labelText null //progressBarText ); final SwingWorker<List<ImageWrapper>, Void> worker = new SwingWorker<List<ImageWrapper>, Void>() { @Override protected List<ImageWrapper> doInBackground() throws DocumentAddException { List<ImageWrapper> retValue = new LinkedList<>(); try { InputStream pdfInputStream = new FileInputStream(documentFile); try (PDDocument document = PDDocument.load(pdfInputStream)) { PDFRenderer pdfRenderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); page++) { if (dialog.isCanceled()) { document.close(); LOGGER.debug("tab generation aborted"); return null; } BufferedImage image = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); ImageWrapper imageWrapper = new CachingImageWrapper(imageWrapperStorageDir, image, issueHandler); retValue.add(imageWrapper); } } } catch (IOException ex) { throw new DocumentAddException(ex); } return retValue; } @Override protected void done() { } }; worker.addPropertyChangeListener(new SwingWorkerCompletionWaiter(dialog)); worker.execute(); //the dialog will be visible until the SwingWorker is done dialog.setVisible(true); List<ImageWrapper> retValue = worker.get(); return retValue; }
From source file:richtercloud.document.scanner.it.ImageStorageIT.java
License:Open Source License
@Test public void testImageStorage() throws IOException, StorageException, SQLException, InterruptedException, StorageConfValidationException, StorageCreationException, OSNotRecognizedException, ArchitectureNotRecognizedException, ExtractionException, MissingSystemBinary, BuildFailureException, ModuleBuildFailureException, FieldOrderValidationException, ImageWrapperException { LOGGER.info("testImageStorage"); try {//from w w w. j ava 2 s. c om new JFXPanel(); //- necessary in order to avoid //`java.lang.IllegalStateException: Toolkit not initialized` //- should be run here in order to be catchable at a useful //location; figure out how to do this if there's more than this //one test File databaseDir = Files.createTempDirectory(ImageStorageIT.class.getSimpleName()).toFile(); FileUtils.forceDelete(databaseDir); //databaseDir mustn't exist for Apache Derby LOGGER.debug(String.format("database directory is %s", databaseDir.getAbsolutePath())); File schemeChecksumFile = File.createTempFile(ImageStorageIT.class.getSimpleName(), "scheme-checksum"); LOGGER.debug(String.format("scheme checksum file is %s", schemeChecksumFile.getAbsolutePath())); File imageStorageDir = Files.createTempDirectory(ImageStorageIT.class.getSimpleName()).toFile(); LOGGER.debug(String.format("image storage directory is %s", imageStorageDir.getAbsolutePath())); Connection connection = DriverManager .getConnection(String.format("jdbc:derby:%s;create=true", databaseDir.getAbsolutePath())); connection.close(); Set<Class<?>> entityClasses = new HashSet<Class<?>>( Arrays.asList(EntityByteArray.class, EntityImageIcon.class)); // DerbyNetworkPersistenceStorageConf storageConf = new DerbyNetworkPersistenceStorageConf(entityClasses, // "localhost", // schemeChecksumFile); // storageConf.setDatabaseDir(databaseDir); // storageConf.setPassword("sa"); // PersistenceStorage storage = new DerbyNetworkPersistenceStorage(storageConf, // "richtercloud_document-scanner-it_jar_1.0-SNAPSHOTPU"); DerbyEmbeddedPersistenceStorageConf storageConf = new DerbyEmbeddedPersistenceStorageConf(entityClasses, databaseDir.getAbsolutePath(), schemeChecksumFile); String persistenceUnitName = "document-scanner-it"; FieldRetriever fieldRetriever = new JPAOrderedCachedFieldRetriever( Constants.QUERYABLE_AND_EMBEDDABLE_CLASSES); final PersistenceStorage<Long> derbyEmbeddedStorage1 = new DerbyEmbeddedPersistenceStorage(storageConf, persistenceUnitName, 1, //parallelQueryCount fieldRetriever); derbyEmbeddedStorage1.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { LOGGER.info("shutting down storage"); derbyEmbeddedStorage1.shutdown(); LOGGER.info("storage shut down"); try { FileUtils.deleteDirectory(databaseDir); LOGGER.info(String.format("database directory '%s' deleted", databaseDir.getAbsolutePath())); } catch (IOException ex) { LOGGER.info(String.format( "deletion of database directory '%s' failed, see nested exception for details", databaseDir.getAbsolutePath()), ex); } try { FileUtils.deleteDirectory(imageStorageDir); } catch (IOException ex) { java.util.logging.Logger.getLogger(ImageStorageIT.class.getName()).log(Level.SEVERE, null, ex); } }, String.format("%s shutdown hook", ImageStorageIT.class.getSimpleName()))); List<ImageIcon> imageIcons = new LinkedList<>(); InputStream pdfInputStream = ImageStorageIT.class.getResourceAsStream("/image_data.pdf"); assert pdfInputStream != null; PDDocument document = PDDocument.load(pdfInputStream); @SuppressWarnings("unchecked") List<OCRSelectPanel> oCRSelectPanels = new LinkedList<>(); List<ImageWrapper> imageWrappers = new LinkedList<>(); byte[] data; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); PDFRenderer pdfRenderer = new PDFRenderer(document); IssueHandler issueHandler = new LoggerIssueHandler(LOGGER); for (int page = 0; page < document.getNumberOfPages(); page++) { BufferedImage image = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); ImageWrapper imageWrapper = new CachingImageWrapper(databaseDir, image, issueHandler); OCRSelectPanel oCRSelectPanel = new DefaultOCRSelectPanel(imageWrapper, DocumentScannerConf.PREFERRED_SCAN_RESULT_PANEL_WIDTH_DEFAULT, issueHandler); oCRSelectPanels.add(oCRSelectPanel); ImageIcon imageIcon = new ImageIcon(image); objectOutputStream.writeObject(imageIcon); imageIcons.add(imageIcon); imageWrappers.add(new CachingImageWrapper(imageStorageDir, image, issueHandler)); } document.close(); data = outputStream.toByteArray(); EntityByteArray entityA = new EntityByteArray(1L, data); EntityByteArray entityA2 = new EntityByteArray(3L, data); EntityImageIcon entityB = new EntityImageIcon(2L, imageIcons); EntityImageIcon entityB2 = new EntityImageIcon(4L, imageIcons); EntityImageWrapper entityC1 = new EntityImageWrapper(imageWrappers); EntityImageWrapper entityC2 = new EntityImageWrapper(imageWrappers); long time0 = System.currentTimeMillis(); entityA.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityA)); derbyEmbeddedStorage1.store(entityA); long time1 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA: %d ms", time1 - time0)); entityB.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityB)); derbyEmbeddedStorage1.store(entityB); long time2 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityB: %d ms", time2 - time1)); //store another time in order to figure out caching effects entityA2.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityA2)); derbyEmbeddedStorage1.store(entityA2); long time3 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA2: %d ms", time3 - time2)); entityB2.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityB2)); derbyEmbeddedStorage1.store(entityB2); long time4 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityB2: %d ms", time4 - time3)); entityC1.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityC1)); derbyEmbeddedStorage1.store(entityC1); long time5 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityC1: %d ms", time5 - time4)); entityC2.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityC2)); derbyEmbeddedStorage1.store(entityC2); long time6 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityC2: %d ms", time6 - time5)); LOGGER.info(String.format("size of entityA's data: %d KiB", entityA.getData().length / 1024)); long randomSeed = System.currentTimeMillis(); LOGGER.info(String.format("random seed is: %d", randomSeed)); Random random = new Random(randomSeed); byte[] referenceBytes = new byte[data.length]; random.nextBytes(referenceBytes); EntityByteArray entityA3 = new EntityByteArray(5L, referenceBytes); EntityByteArray entityA4 = new EntityByteArray(6L, referenceBytes); long time7 = System.currentTimeMillis(); entityA3.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityA3)); derbyEmbeddedStorage1.store(entityA3); long time8 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA3: %d ms", time8 - time7)); entityA4.setId(MemorySequentialIdGenerator.getInstance().getNextId(entityA4)); derbyEmbeddedStorage1.store(entityA4); long time9 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA4: %d ms", time9 - time8)); derbyEmbeddedStorage1.shutdown(); //test whether EntityImagerWrapper is deserializable PersistenceStorage<Long> derbyEmbeddedStorage2 = new DerbyEmbeddedPersistenceStorage(storageConf, persistenceUnitName, 1, //parallelQueryCount fieldRetriever); derbyEmbeddedStorage2.start(); List<EntityImageWrapper> queryResults = derbyEmbeddedStorage2.runQueryAll(EntityImageWrapper.class); assert queryResults.size() == 2; EntityImageWrapper queryResult0 = queryResults.get(0); List<ImageWrapper> queryResult0Data = queryResult0.getData(); for (ImageWrapper queryResult0Datum : queryResult0Data) { LOGGER.info(String.format("inspect image wrapper file %s ms", queryResult0Datum.getStorageFile())); } derbyEmbeddedStorage2.shutdown(); //test PostgreSQL File databaseDirPostgresql = Files.createTempDirectory(ImageStorageIT.class.getSimpleName()).toFile(); FileUtils.forceDelete(databaseDirPostgresql); //an inexisting database directory triggers creation of database //with initdb LOGGER.debug( String.format("PostgreSQL database directory is %s", databaseDirPostgresql.getAbsolutePath())); //build PostgreSQL File postgresqlInstallationPrefixDir = Files.createTempDirectory(ImageStorageIT.class.getSimpleName()) .toFile(); LOGGER.debug(String.format("using '%s' as PostgreSQL installation prefix", postgresqlInstallationPrefixDir.getAbsolutePath())); File downloadDir = Files.createTempDirectory(ImageStorageIT.class.getSimpleName()).toFile(); //SystemUtils.getUserHome() causes trouble //($HOME/jhbuild/checkout might be jhbuilds default extraction //directory) LOGGER.debug(String.format("using '%s' as JHBuild Java wrapper download directory", downloadDir)); JHBuildJavaWrapper jHBuildJavaWrapper = new JHBuildJavaWrapper(postgresqlInstallationPrefixDir, //installationPrefixDir downloadDir, //downloadDir ActionOnMissingBinary.DOWNLOAD, ActionOnMissingBinary.DOWNLOAD, new AutoDownloader(), //downloader false, true, //silenceStdout true, //silenceStderr issueHandler); String moduleName = "postgresql-9.6.3"; LOGGER.info( String.format("building module %s from JHBuild Java wrapper's default moduleset", moduleName)); jHBuildJavaWrapper.installModuleset(moduleName); //moduleset shipped with jhbuild-java-wrapper String initdb = new File(postgresqlInstallationPrefixDir, String.join(File.separator, "bin", "initdb")) .getAbsolutePath(); String postgres = new File(postgresqlInstallationPrefixDir, String.join(File.separator, "bin", "postgres")).getAbsolutePath(); String createdb = new File(postgresqlInstallationPrefixDir, String.join(File.separator, "bin", "createdb")).getAbsolutePath(); String pgCtl = new File(postgresqlInstallationPrefixDir, String.join(File.separator, "bin", "pg_ctl")) .getAbsolutePath(); String databaseName = "image-storage-it"; String username = "docu"; String password = "docu"; PostgresqlAutoPersistenceStorageConf postgresqlPersistenceStorageConf = new PostgresqlAutoPersistenceStorageConf( entityClasses, "localhost", //hostname username, //username password, databaseName, schemeChecksumFile, databaseDirPostgresql.getAbsolutePath(), //databaseDir initdb, postgres, createdb, pgCtl); PersistenceStorage<Long> postgresqlStorage = new PostgresqlAutoPersistenceStorage( postgresqlPersistenceStorageConf, persistenceUnitName, 1, //parallelQueryCount fieldRetriever, issueHandler); postgresqlStorage.start(); time0 = System.currentTimeMillis(); postgresqlStorage.store(entityA); time1 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA: %d ms", time1 - time0)); postgresqlStorage.store(entityB); time2 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityB: %d ms", time2 - time1)); //store another time in order to figure out caching effects postgresqlStorage.store(entityA2); time3 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA2: %d ms", time3 - time2)); postgresqlStorage.store(entityB2); time4 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityB2: %d ms", time4 - time3)); LOGGER.info(String.format("size of entityA's data: %d KiB", entityA.getData().length / 1024)); time9 = System.currentTimeMillis(); postgresqlStorage.store(entityA3); time8 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA3: %d ms", time8 - time9)); postgresqlStorage.store(entityA4); time9 = System.currentTimeMillis(); LOGGER.info(String.format("time for storing entityA4: %d ms", time9 - time8)); postgresqlStorage.shutdown(); Caching.getCachingProvider().close(); } catch (UnsupportedOperationException ex) { //`new JFXPanel()` for JavaFX toolkit initialization causes //`java.lang.UnsupportedOperationException: Unable to open DISPLAY` //instead of HeadlessException (which is a subclass of //UnsupportedOperationException LOGGER.warn( "UnsupportedOperationException indicates that the test is run on a headless machine, e.g. a CI service", ex); } }
From source file:src.controller.DocumentController.java
/** * Convertion en image/*from w w w .j a v a2s . co m*/ * * @param file * @param extension */ public void convertToImage(File file, String extension) { PDDocument document; try { document = PDDocument.load(file); PDFRenderer pdfRenderer = new PDFRenderer(document); int pageCounter = 0; for (PDPage lapage : document.getPages()) { // note that the page number parameter is zero based BufferedImage bim = pdfRenderer.renderImageWithDPI(pageCounter, 300, ImageType.RGB); // suffix in filename will be used as the file format ImageIOUtil.writeImage(bim, file + "-" + (pageCounter++) + extension, 300); } document.close(); } catch (IOException ex) { Logger.getLogger(DocumentController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:src.view.displayer.PageDisplayer.java
/** * Transforme la page actuelle en image//from w w w. j a v a 2 s . com * * @param imagePDF * @param pageIndex */ public static void setImage(ImageView imagePDF, int pageIndex, DocFile docFile) { try { PDFRenderer renderer = new PDFRenderer(docFile.getDocument()); // Transformation de la page en image BufferedImage bufferedImage = renderer.renderImageWithDPI(pageIndex, PDF_DISPLAY_DPI); WritableImage image = SwingFXUtils.toFXImage(bufferedImage, null); imagePDF.setImage(image); imagePDF.setId("imagePDF"); imagePDF.setStyle("-fx-effect: dropshadow(three-pass-box, black, 100, 0, 0, 0);"); // On met l'image sous la mme forme (paysage, portrait) que la page imagePDF.setFitWidth(bufferedImage.getWidth() * docFile.getZoom() * INITIAL_SCALE / 100); imagePDF.setFitHeight(bufferedImage.getHeight() * docFile.getZoom() * INITIAL_SCALE / 100); } catch (IOException e) { System.out.println(e.toString()); } }
From source file:ve.zoonosis.utils.PDFCreator.java
License:Apache License
public BufferedImage getImagePage(int index) throws IOException { contentStream.close();// w ww .j a va2 s.co m PDFRenderer pdfRenderer = new PDFRenderer(document); return pdfRenderer.renderImage(index, 1f, ImageType.RGB); }