org.apache.pdfbox.rendering.PDFRenderer Java Examples
The following examples show how to use
org.apache.pdfbox.rendering.PDFRenderer.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PdfBoxConverter.java From workable-converter with GNU General Public License v3.0 | 8 votes |
@Override public boolean byFileFolder(ConvertRequire require) throws ConvertFailedException { logger.info("pdfbox convert by file folder begin(src file must be a pdf file) :"); try { File srcFile = new File(require.getWaitingFilePath()); PDDocument document = PDDocument.load(srcFile); PDFRenderer renderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); page++) { BufferedImage image = renderer.renderImageWithDPI(page, 300, ImageType.RGB); String savename = require.getDestConvertedPath() + "/" + SuffixTool.deleteSuffix(srcFile.getName()) + "_" + page + ".png"; ImageIOUtil.writeImage(image, savename, 300); } document.close(); } catch (Exception e) { throw new ConvertFailedException(e.getMessage()); } logger.info("pdf box convert by filepath success"); return true; }
Example #2
Source File: PdfBoxConverter.java From workable-converter with GNU General Public License v3.0 | 6 votes |
/** * convert a pdf base64 file to png pics */ @Override public boolean byBase64 (ConvertRequire require) throws ConvertFailedException { logger.info("pdfbox convert by base64 begin(src file must be a pdf file):"); try { String srcFileTmpName = StrRandomTool.getUuid(true) + ".pdf"; Base64FileTool.saveBase64File(require.getSrcBase64(), params.getTmpPath() + "/" + srcFileTmpName); File srcFile = new File(params.getTmpPath() + "/" + srcFileTmpName); PDDocument document = PDDocument.load(srcFile); PDFRenderer renderer = new PDFRenderer(document); List<String> results = new LinkedList<>(); for (int page = 0; page < document.getNumberOfPages(); page++) { BufferedImage image = renderer.renderImageWithDPI(page, 300, ImageType.RGB); String savePath = params.getTmpPath() + "/" + SuffixTool.deleteSuffix(srcFile.getName()) + "_" + page + ".png"; ImageIOUtil.writeImage(image, savePath, 300); results.add(Base64FileTool.filePathToBase64(savePath)); } require.setDestBase64s(results); document.close(); } catch (Exception e) { throw new ConvertFailedException(e.getMessage()); } logger.info("pdf box convert by base64 success"); return true; }
Example #3
Source File: PdfService.java From cs-actions with Apache License 2.0 | 6 votes |
private static List<File> iteration(String destination, Integer dpi, PDFRenderer renderer, List<File> fileList, String fileName, Integer fromPage, Integer toPage, String pageIndex) throws IOException { if (!pageIndex.equals(EMPTY)) { final String[] arrSplit = pageIndex.split(COMMA); for (String anArrSplit : arrSplit) { int val = Integer.parseInt(anArrSplit); fileCreation(destination, dpi, renderer, fileList, fileName, --val); } } else { for (int i = fromPage; i < toPage; i++) { // default image files path: original file path // if necessary, file.getParent() + "/" => another path fileCreation(destination, dpi, renderer, fileList, fileName, i); } } return fileList; }
Example #4
Source File: PDFPreviewBuilder.java From Open-LaTeX-Studio with MIT License | 6 votes |
public static Image buildPDFPreview(int page, int zoom) { float newScale = ((float) zoom) / 100.0f; BufferedImage pageImage = null; try (PDDocument pdDocument = PDFService.getPDDocument()) { PDFRenderer pdfRenderer = new PDFRenderer(pdDocument); if (pdDocument.getNumberOfPages() >= page && page > 0){ pageImage = pdfRenderer.renderImage(page - 1); int width = (int) (newScale * pageImage.getWidth()); int height = (int) (newScale * pageImage.getHeight()); return pageImage.getScaledInstance(width, height, SCALE_TYPE); } return pageImage; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; }
Example #5
Source File: PdfScreenshotUtils.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
public static void checkPdfSimilarity(PDDocument document1, PDDocument document2, float minSimilarity) throws IOException { PDPageTree samplePageTree = document1.getPages(); PDPageTree checkPageTree = document2.getPages(); assertEquals(checkPageTree.getCount(), samplePageTree.getCount()); PDFRenderer sampleRenderer = new PDFRenderer(document1); PDFRenderer checkRenderer = new PDFRenderer(document2); for (int pageNumber = 0; pageNumber < checkPageTree.getCount(); pageNumber++) { BufferedImage sampleImage = sampleRenderer.renderImageWithDPI(pageNumber, DPI); BufferedImage checkImage = checkRenderer.renderImageWithDPI(pageNumber, DPI); // ImageIO.write(sampleImage, "png", new File("target\\sampleImage.png")); // ImageIO.write(checkImage, "png", new File("target\\checkImage.png")); float checkSimilarity = checkImageSimilarity(sampleImage, checkImage, CHECK_RESOLUTION); assertTrue(checkSimilarity >= minSimilarity, "The image similarity " + checkSimilarity + " is lower the allowed limit " + minSimilarity); } }
Example #6
Source File: RenderPage.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/45831641/read-pdf-written-in-chinese-using-java"> * read pdf written in chinese using java * </a> * <br/> * <a href="https://drive.google.com/file/d/0B6k7AYGPEth2djFMNVJ0dC1wLVU/view?usp=sharing"> * sample1.pdf * </a> * <p> * Cannot reproduce the problem with the file at hand without concrete * code. * </p> */ @Test public void testRenderSample1() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("sample1.pdf")) { PDDocument document = Loader.loadPDF(resource); PDFRenderer renderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); page++) { BufferedImage image = renderer.renderImageWithDPI(page, 96); File result = new File(RESULT_FOLDER, String.format("sample1-%s.png", page)); ImageIO.write(image, "PNG", result); } } }
Example #7
Source File: SetCropBox.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/39689004/pdfbox-2-0-3-set-cropbox-using-textposition-coordinates"> * PDFBox 2.0.3 Set cropBox using TextPosition coordinates * </a> * <br/> * <a href="http://downloadcenter.samsung.com/content/UM/201504/20150407095631744/ENG-US_NMATSCJ-1.103-0330.pdf"> * ENG-US_NMATSCJ-1.103-0330.pdf * </a> * <p> * This test shows how to set the crop box on page twelve and render the cropped page as image. * </p> */ @Test public void testSetCropBoxImgENG_US_NMATSCJ_1_103_0330() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("ENG-US_NMATSCJ-1.103-0330.pdf")) { PDDocument pdDocument = Loader.loadPDF(resource); PDPage page = pdDocument.getPage(12-1); page.setCropBox(new PDRectangle(40f, 680f, 510f, 100f)); PDFRenderer renderer = new PDFRenderer(pdDocument); BufferedImage img = renderer.renderImage(12 - 1, 4f); ImageIOUtil.writeImage(img, new File(RESULT_FOLDER, "ENG-US_NMATSCJ-1.103-0330-page12cropped.jpg").getAbsolutePath(), 300); pdDocument.close(); } }
Example #8
Source File: PdfComparator.java From pdfcompare with Apache License 2.0 | 6 votes |
private void addExtraPages(final PDDocument document, final PDFRenderer pdfRenderer, final int minPageCount, final int color, final boolean expected) throws IOException { for (int pageIndex = minPageCount; pageIndex < document.getNumberOfPages(); pageIndex++) { ImageWithDimension image = renderPageAsImage(document, pdfRenderer, pageIndex, environment); final DataBuffer dataBuffer = image.bufferedImage.getRaster().getDataBuffer(); for (int i = 0; i < image.bufferedImage.getWidth() * MARKER_WIDTH; i++) { dataBuffer.setElem(i, color); } for (int i = 0; i < image.bufferedImage.getHeight(); i++) { for (int j = 0; j < MARKER_WIDTH; j++) { dataBuffer.setElem(i * image.bufferedImage.getWidth() + j, color); } } if (expected) { compareResult.addPage(new PageDiffCalculator(new PageArea(pageIndex + 1)), pageIndex, image, blank(image), image); } else { compareResult.addPage(new PageDiffCalculator(new PageArea(pageIndex + 1)), pageIndex, blank(image), image, image); } } }
Example #9
Source File: PdfComparator.java From pdfcompare with Apache License 2.0 | 6 votes |
private void drawImage(final CountDownLatch latch, final int pageIndex, final PDDocument expectedDocument, final PDDocument actualDocument, final PDFRenderer expectedPdfRenderer, final PDFRenderer actualPdfRenderer) { drawExecutor.execute(() -> { try { LOG.trace("Drawing page {}", pageIndex); final Future<ImageWithDimension> expectedImageFuture = parrallelDrawExecutor .submit(() -> renderPageAsImage(expectedDocument, expectedPdfRenderer, pageIndex, environment)); final Future<ImageWithDimension> actualImageFuture = parrallelDrawExecutor .submit(() -> renderPageAsImage(actualDocument, actualPdfRenderer, pageIndex, environment)); final ImageWithDimension expectedImage = getImage(expectedImageFuture, pageIndex, "expected document"); final ImageWithDimension actualImage = getImage(actualImageFuture, pageIndex, "actual document"); final DiffImage diffImage = new DiffImage(expectedImage, actualImage, pageIndex, environment, getExclusions(), compareResult); LOG.trace("Enqueueing page {}.", pageIndex); diffExecutor.execute(() -> { LOG.trace("Diffing page {}", diffImage); diffImage.diffImages(); LOG.trace("DONE Diffing page {}", diffImage); }); LOG.trace("DONE drawing page {}", pageIndex); } catch (RenderingException e) { } finally { latch.countDown(); } }); }
Example #10
Source File: PdfComparator.java From pdfcompare with Apache License 2.0 | 6 votes |
private void compare(final PDDocument expectedDocument, final PDDocument actualDocument) throws IOException { expectedDocument.setResourceCache(new ResourceCacheWithLimitedImages(environment)); PDFRenderer expectedPdfRenderer = new PDFRenderer(expectedDocument); actualDocument.setResourceCache(new ResourceCacheWithLimitedImages(environment)); PDFRenderer actualPdfRenderer = new PDFRenderer(actualDocument); final int minPageCount = Math.min(expectedDocument.getNumberOfPages(), actualDocument.getNumberOfPages()); CountDownLatch latch = new CountDownLatch(minPageCount); for (int pageIndex = 0; pageIndex < minPageCount; pageIndex++) { drawImage(latch, pageIndex, expectedDocument, actualDocument, expectedPdfRenderer, actualPdfRenderer); } Utilities.await(latch, "FullCompare", environment); Utilities.shutdownAndAwaitTermination(drawExecutor, "Draw"); Utilities.shutdownAndAwaitTermination(parrallelDrawExecutor, "Parallel Draw"); Utilities.shutdownAndAwaitTermination(diffExecutor, "Diff"); if (expectedDocument.getNumberOfPages() > minPageCount) { addExtraPages(expectedDocument, expectedPdfRenderer, minPageCount, environment.getActualColor().getRGB(), true); } else if (actualDocument.getNumberOfPages() > minPageCount) { addExtraPages(actualDocument, actualPdfRenderer, minPageCount, environment.getExpectedColor().getRGB(), false); } }
Example #11
Source File: MCRPdfThumbnailGenerator.java From mycore with GNU General Public License v3.0 | 6 votes |
@Override public Optional<BufferedImage> getThumbnail(MCRPath path, int size) throws IOException { try (InputStream fileIS = Files.newInputStream(path); PDDocument pdf = PDDocument.load(fileIS)) { final PDPage page = resolveOpenActionPage(pdf); float pdfWidth = page.getCropBox().getWidth(); float pdfHeight = page.getCropBox().getHeight(); final int newWidth = pdfWidth > pdfHeight ? (int) Math.ceil(size * pdfWidth / pdfHeight) : size; final float scale = newWidth / pdfWidth; PDFRenderer pdfRenderer = new PDFRenderer(pdf); BufferedImage pdfRender = pdfRenderer.renderImage(pdf.getPages().indexOf(page), scale); int imageType = MCRThumbnailUtils.getImageType(pdfRender); if (imageType == BufferedImage.TYPE_BYTE_BINARY || imageType == BufferedImage.TYPE_BYTE_GRAY) { BufferedImage thumbnail = new BufferedImage(pdfRender.getWidth(), pdfRender.getHeight(), imageType); Graphics g = thumbnail.getGraphics(); g.drawImage(pdfRender, 0, 0, null); g.dispose(); return Optional.of(thumbnail); } return Optional.of(pdfRender); } }
Example #12
Source File: PdfRenderer.java From gcs with Mozilla Public License 2.0 | 6 votes |
public static BufferedImage create(PDDocument pdf, int pageIndex, float scale, String textToHighlight) { try { PDFRenderer renderer = new PDFRenderer(pdf); scale = scale * Toolkit.getDefaultToolkit().getScreenResolution() / 72.0f; BufferedImage img = renderer.renderImage(pageIndex, scale); if (textToHighlight != null) { Graphics2D gc = img.createGraphics(); gc.setStroke(new BasicStroke(0.1f)); gc.scale(scale, scale); PdfRenderer processor = new PdfRenderer(gc, textToHighlight); processor.setSortByPosition(true); processor.setStartPage(pageIndex + 1); processor.setEndPage(pageIndex + 1); try (DummyWriter writer = new DummyWriter()) { processor.writeText(pdf, writer); } gc.dispose(); } return img; } catch (Exception exception) { Log.error(exception); return null; } }
Example #13
Source File: PdfTableReader.java From pdf-table with MIT License | 6 votes |
/** * Saves debug images of PDF pages from specified range and saves them in specified directory. * * @param document PDF document instance * @param startPage first page in range to process (first page == 1) * @param endPage last page in range * @param outputDir destination directory * @throws IOException */ public void savePdfTablePagesDebugImages(PDDocument document, int startPage, int endPage, Path outputDir) throws IOException { TableExtractor debugExtractor = new TableExtractor(settings); PDFRenderer renderer = new PDFRenderer(document); for (int page = startPage - 1; page < endPage; ++page) { PdfTableSettings debugSettings = PdfTableSettings.getBuilder() .setDebugImages(true) .setDebugFileOutputDir(outputDir) .setDebugFilename("page_" + (page + 1)) .build(); debugExtractor.setSettings(debugSettings); BufferedImage bi; synchronized (this) { bi = renderer.renderImageWithDPI(page, settings.getPdfRenderingDpi(), ImageType.RGB); } debugExtractor.getTableBoundingRectangles(bufferedImage2GrayscaleMat(bi)); } }
Example #14
Source File: ConvertTest.java From blog-codes with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InvalidPasswordException, IOException { PDDocument document = PDDocument.load(new File("/home/lili/data/testen.pdf")); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); ++page) { if(page>0 && page %100==0) { System.out.println("page: "+page); } // float w=document.getPage(page).getMediaBox().getWidth(); // float h=document.getPage(page).getMediaBox().getHeight(); // System.out.println(String.format("w: %f, h: %f",w, h)); BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); //BufferedImage bim = pdfRenderer.renderImage(page, 2.0f); // suffix in filename will be used as the file format ImageIOUtil.writeImage(bim, "/home/lili/data/testen-" + (page + 1) + ".png", 300); } }
Example #15
Source File: PdfSlide.java From Quelea with GNU General Public License v3.0 | 6 votes |
/** * Create a new PDF slide. * * @param numSlide slide number * @param pdfRenderer the renderer of the file */ public PdfSlide(int numSlide, PDFRenderer pdfRenderer) throws IOException { originalImage = resizeImage(pdfRenderer.renderImageWithDPI(numSlide - 1, 200, ImageType.RGB), BIG_SIZE, BIG_SIZE); outputfile = File.createTempFile("slide" + numSlide, ".png"); outputfile.deleteOnExit(); ImageIO.write(originalImage, "png", outputfile); thumbnail = resizeImage(originalImage, QueleaProperties.get().getThumbnailSize(), QueleaProperties.get().getThumbnailSize()); thumbnailFile = File.createTempFile("thumb" + numSlide, ".png"); thumbnailFile.deleteOnExit(); ImageIO.write(thumbnail, "png", thumbnailFile); originalImage.flush(); originalImage = null; thumbnail.flush(); thumbnail = null; }
Example #16
Source File: PDFPresentation.java From Quelea with GNU General Public License v3.0 | 5 votes |
/** * Make the slides that go in this PDF, this is what takes time and should * only be done once. * * @return all the slides. */ private PdfSlide[] makeSlides() throws IOException { File pdf = new File(file); PDDocument document = PDDocument.load(pdf.getAbsoluteFile()); Path f = Files.createTempDirectory(null); f.toFile().deleteOnExit(); ArrayList<PdfSlide> ret = new ArrayList<>(); PDFRenderer pdfRenderer = new PDFRenderer(document); int totalPages = document.getNumberOfPages(); for (int i = 0; i < totalPages; i++) { ret.add(new PdfSlide(i + 1, pdfRenderer)); } document.close(); return ret.toArray(new PdfSlide[ret.size()]); }
Example #17
Source File: PDF2ImageExample.java From tutorials with MIT License | 5 votes |
private static void generateImageFromPDF(String filename, String extension) throws IOException { PDDocument document = PDDocument.load(new File(filename)); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); ++page) { BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); ImageIOUtil.writeImage(bim, String.format("src/output/pdf-%d.%s", page + 1, extension), 300); } document.close(); }
Example #18
Source File: DefaultDocumentTest.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
@Test public void testToImage() throws Exception { testRender(); PDDocument pdf = PDDocument.load(new File("target/test.pdf"), true); PDFRenderer renderer = new PDFRenderer(pdf); BufferedImage bufferedImage = renderer.renderImageWithDPI(0, 144); pdf.close(); ImageIO.write(bufferedImage, "PNG", new File("target/test.png")); }
Example #19
Source File: SinglePageDocument.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
private void writeDocument(OutputStream outputStream, Format format, int dpi) throws IOException, DocumentException, PrintingException { if (format == Format.PDF) { baos.writeTo(outputStream); } else { PDDocument pdf = PDDocument.load(new ByteArrayInputStream(baos.toByteArray()), true); PDFRenderer renderer = new PDFRenderer(pdf); BufferedImage bufferedImage = renderer.renderImageWithDPI(0, dpi); pdf.close(); if (format == Format.PNG) { final String formatName = format.getExtension(); for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) { ImageWriter writer1 = iw.next(); ImageWriteParam writeParam = writer1.getDefaultWriteParam(); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier .createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB); IIOMetadata metadata = writer1.getDefaultImageMetadata(typeSpecifier, writeParam); if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) { continue; } setDPI(metadata); // Write bufferedImage to outputStream final ImageOutputStream stream = ImageIO.createImageOutputStream(outputStream); try { writer1.setOutput(stream); writer1.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam); } finally { stream.flush(); stream.close(); } break; } } else { ImageIO.write(bufferedImage, format.getExtension(), outputStream); } } }
Example #20
Source File: PdfService.java From cs-actions with Apache License 2.0 | 5 votes |
private static void fileCreation(String destination, Integer dpi, PDFRenderer renderer, List<File> fileList, String fileName, Integer i) throws IOException { File fileTemp = new File(destination + fileName + UNDERSCORE + RandomStringUtils.randomAlphanumeric(15).toUpperCase() + PNG_EXTENSION); // jpg or png BufferedImage image = renderer.renderImageWithDPI(i, dpi); // if necessary, change 200 into another integer. ImageIO.write(image, PNG, fileTemp); // JPEG or PNG fileList.add(fileTemp); }
Example #21
Source File: PdfService.java From cs-actions with Apache License 2.0 | 5 votes |
private static List<File> convertPdfToImage(File file, String destination, String dpi, String fromPage, String toPage, String pageIndex) throws Exception { if (file.exists()) { PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); List<File> fileList = new ArrayList<>(); String fileName = file.getName().replace(PDF_EXTENSION, EMPTY); if (StringUtils.equals(fromPage, EMPTY) && StringUtils.equals(toPage, EMPTY) && StringUtils.equals(pageIndex, EMPTY)) fileList = PdfService.iteration(destination, Integer.parseInt(dpi), renderer, fileList, fileName, 0, doc.getNumberOfPages(), pageIndex); if (StringUtils.equals(fromPage, EMPTY) && !StringUtils.equals(toPage, EMPTY) && StringUtils.equals(pageIndex, EMPTY)) fileList = PdfService.iteration(destination, Integer.parseInt(dpi), renderer, fileList, fileName, 0, Integer.parseInt(toPage), pageIndex); if (!StringUtils.equals(fromPage, EMPTY) && !StringUtils.equals(toPage, EMPTY) && StringUtils.equals(pageIndex, EMPTY)) { int fromPageImp = Integer.parseInt(fromPage); fileList = PdfService.iteration(destination, Integer.parseInt(dpi), renderer, fileList, fileName, --fromPageImp, Integer.parseInt(toPage), pageIndex); } if (!StringUtils.equals(pageIndex, EMPTY)) fileList = iteration(destination, Integer.parseInt(dpi), renderer, fileList, fileName, 0, 0, pageIndex); doc.close(); return fileList; } throw new Exception(FILE_NOT_EXISTS); }
Example #22
Source File: PDFPreviewGenerator.java From FXDesktopSearch with Apache License 2.0 | 5 votes |
@Override public Preview createPreviewFor(final File aFile) { try(final var theDocument = PDDocument.load(aFile)) { final var thePages = theDocument.getPages(); if (thePages.getCount() == 0) { return null; } final var theFirstPage = thePages.get(0); final var mBox = theFirstPage.getMediaBox(); final var theWidthPt = mBox.getWidth(); final var theWidthPx = THUMB_WIDTH; // Math.round(widthPt * scaling); final var theHeightPx = THUMB_HEIGHT; // Math.round(heightPt * scaling); final var theScaling = THUMB_WIDTH / theWidthPt; // resolution / 72.0F; final var theImage = new BufferedImage(theWidthPx, theHeightPx, BufferedImage.TYPE_INT_RGB); final var theGraphics = (Graphics2D) theImage.getGraphics(); theGraphics.setBackground(new Color(255, 255, 255, 0)); theGraphics.clearRect(0, 0, theImage.getWidth(), theImage.getHeight()); final var theRenderer = new PDFRenderer(theDocument); theRenderer.renderPageToGraphics(0, theGraphics, theScaling); final var rotation = theFirstPage.getRotation(); if ((rotation == 90) || (rotation == 270)) { final var w = theImage.getWidth(); final var h = theImage.getHeight(); final var rotatedImg = new BufferedImage(w, h, theImage.getType()); final var g = rotatedImg.createGraphics(); g.rotate(Math.toRadians(rotation), w / 2, h / 2); g.drawImage(theImage, null, 0, 0); } theGraphics.dispose(); return new Preview(theImage); } catch (final Exception e) { log.error("Error creating preview for {}", aFile, e); return null; } }
Example #23
Source File: Utils.java From tabula-java with MIT License | 5 votes |
public static BufferedImage pageConvertToImage(PDPage page, int dpi, ImageType imageType) throws IOException { try (PDDocument document = new PDDocument()) { document.addPage(page); PDFRenderer renderer = new PDFRenderer(document); document.close(); return renderer.renderImageWithDPI(0, dpi, imageType); } }
Example #24
Source File: PdfConvertUtils.java From bamboobsc with Apache License 2.0 | 5 votes |
public static List<File> toImageFiles(File pdfFile, int resolution) throws Exception { PDDocument document = PDDocument.load(pdfFile); PDFRenderer pdfRenderer = new PDFRenderer(document); /* List<PDPage> pages = new LinkedList<PDPage>(); for (int i=0; i < document.getDocumentCatalog().getPages().getCount(); i++) { pages.add( document.getDocumentCatalog().getPages().get(i) ); } */ File tmpDir = new File(Constants.getWorkTmpDir() + "/" + PdfConvertUtils.class.getSimpleName() + "/" + System.currentTimeMillis() + "/"); FileUtils.forceMkdir( tmpDir ); List<File> files = new LinkedList<File>(); //int len = String.valueOf(pages.size()+1).length(); int len = String.valueOf(document.getDocumentCatalog().getPages().getCount()+1).length(); //for (int i=0; i<pages.size(); i++) { for (int i=0; i<document.getDocumentCatalog().getPages().getCount(); i++) { String name = StringUtils.leftPad(String.valueOf(i+1), len, "0"); BufferedImage bufImage = pdfRenderer.renderImageWithDPI(i, resolution, ImageType.RGB); File imageFile = new File( tmpDir.getPath() + "/" + name + ".png" ); FileOutputStream fos = new FileOutputStream(imageFile); ImageIOUtil.writeImage(bufImage, "png", fos, resolution); fos.flush(); fos.close(); files.add(imageFile); } document.close(); tmpDir = null; return files; }
Example #25
Source File: PdfTableReader.java From pdf-table with MIT License | 5 votes |
/** * Renders PDF page with DPI specified in settings and saves it in specified directory. * * @param renderer PDF renderer instance * @param page page number * @param outputDir output directory * @throws IOException */ private void savePdfPageAsPNG(PDFRenderer renderer, int page, Path outputDir) throws IOException { BufferedImage bim; synchronized (this) { bim = renderer.renderImageWithDPI(page, settings.getPdfRenderingDpi(), ImageType.RGB); } Path outPath = outputDir.resolve(Paths.get("page_" + (page + 1) + ".png")); ImageIOUtil.writeImage(bim, outPath.toString(), settings.getPdfRenderingDpi()); }
Example #26
Source File: Utilities.java From pdfcompare with Apache License 2.0 | 5 votes |
public static ImageWithDimension renderPage(final InputStream documentIS, final int page, Environment environment) throws IOException { try (PDDocument pdDocument = PDDocument.load(documentIS, Utilities.getMemorySettings(environment.getDocumentCacheSize()))) { if (page >= pdDocument.getNumberOfPages()) { throw new IllegalArgumentException("Page out of range. Last page is: " + pdDocument.getNumberOfPages()); } pdDocument.setResourceCache(new ResourceCacheWithLimitedImages(environment)); PDFRenderer pdfRenderer = new PDFRenderer(pdDocument); return PdfComparator.renderPageAsImage(pdDocument, pdfRenderer, page, environment); } }
Example #27
Source File: PdfInformation.java From MyBox with Apache License 2.0 | 5 votes |
public BufferedImage readPageAsImage(int page, ImageType imageType) { try { if (doc == null) { return null; } PDFRenderer renderer = new PDFRenderer(doc); BufferedImage image = renderer.renderImage(page, 1, imageType); return image; } catch (Exception e) { return null; } }
Example #28
Source File: PdfTableReader.java From pdf-table with MIT License | 5 votes |
/** * Parses range of PDF pages and returns list of lists of rows containing cell texts. * * @param document PDF document instance * @param startPage first page in range to parse (first page == 1) * @param endPage last page in range * @return List of pages * @throws IOException */ public List<ParsedTablePage> parsePdfTablePages(PDDocument document, int startPage, int endPage) throws IOException { List<ParsedTablePage> out = new ArrayList<>(); PDFRenderer renderer = new PDFRenderer(document); for (int page = startPage - 1; page < endPage; ++page) { BufferedImage bi; synchronized (this) { bi = renderer.renderImageWithDPI(page, settings.getPdfRenderingDpi(), ImageType.RGB); } ParsedTablePage parsedTablePage = parsePdfTablePage(bi, document.getPage(page), page + 1); out.add(parsedTablePage); } return out; }
Example #29
Source File: PdfTools.java From MyBox with Apache License 2.0 | 5 votes |
public static BufferedImage page2image(File file, String password, int page, int dpi, ImageType imageType) { try { try ( PDDocument doc = PDDocument.load(file, password, AppVariables.pdfMemUsage)) { PDFRenderer renderer = new PDFRenderer(doc); BufferedImage image = renderer.renderImageWithDPI(page, dpi, imageType); doc.close(); return image; } } catch (Exception e) { logger.debug(e.toString()); return null; } }
Example #30
Source File: PdfTools.java From MyBox with Apache License 2.0 | 5 votes |
public static BufferedImage page2image(File file, String password, int page, float scale, ImageType imageType) { try { try ( PDDocument doc = PDDocument.load(file, password, AppVariables.pdfMemUsage)) { PDFRenderer renderer = new PDFRenderer(doc); BufferedImage image = renderer.renderImage(page, scale, imageType); doc.close(); return image; } } catch (Exception e) { return null; } }