Java Code Examples for org.apache.pdfbox.pdmodel.PDPageContentStream#close()
The following examples show how to use
org.apache.pdfbox.pdmodel.PDPageContentStream#close() .
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: JoinPages.java From testarea-pdfbox2 with Apache License 2.0 | 7 votes |
/** * @see #testJoinSmallAndBig() */ PDDocument prepareSmallPdf() throws IOException { PDDocument document = new PDDocument(); PDPage page = new PDPage(new PDRectangle(72, 72)); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream.setNonStrokingColor(Color.YELLOW); contentStream.addRect(0, 0, 72, 72); contentStream.fill(); contentStream.setNonStrokingColor(Color.BLACK); PDFont font = PDType1Font.HELVETICA; contentStream.beginText(); contentStream.setFont(font, 18); contentStream.newLineAtOffset(2, 54); contentStream.showText("small"); contentStream.newLineAtOffset(0, -48); contentStream.showText("page"); contentStream.endText(); contentStream.close(); return document; }
Example 2
Source File: RotatePageContent.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java"> * Rotate PDF around its center using PDFBox in java * </a> * <p> * This test shows how to rotate the page content around the center of its crop box * and then crop it to make all previously visible content fit. * </p> */ @Test public void testRotateCenterScale() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf") ) { PDDocument document = Loader.loadPDF(resource); PDPage page = document.getDocumentCatalog().getPages().get(0); PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false); Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0); PDRectangle cropBox = page.getCropBox(); float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2; float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2; Rectangle rectangle = cropBox.transform(matrix).getBounds(); float scale = Math.min(cropBox.getWidth() / (float)rectangle.getWidth(), cropBox.getHeight() / (float)rectangle.getHeight()); cs.transform(Matrix.getTranslateInstance(tx, ty)); cs.transform(matrix); cs.transform(Matrix.getScaleInstance(scale, scale)); cs.transform(Matrix.getTranslateInstance(-tx, -ty)); cs.close(); document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center-scale.pdf")); } }
Example 3
Source File: PDFWriter.java From attic-polygene-java with Apache License 2.0 | 6 votes |
private void writeGraphPage( GraphDisplay graphDisplay ) throws IOException { File tFile = File.createTempFile( "envisage", ".png" ); graphDisplay.saveImage( new FileOutputStream( tFile ), "png", 1d ); BufferedImage img = ImageIO.read( tFile ); int w = img.getWidth(); int h = img.getHeight(); int inset = 40; PDRectangle pdRect = new PDRectangle( w + inset, h + inset ); PDPage page = new PDPage(); page.setMediaBox( pdRect ); doc.addPage( page ); PDImageXObject xImage = PDImageXObject.createFromFileByExtension( tFile, doc ); PDPageContentStream contentStream = new PDPageContentStream( doc, page ); contentStream.drawImage( xImage, ( pdRect.getWidth() - w ) / 2, ( pdRect.getHeight() - h ) / 2 ); contentStream.close(); }
Example 4
Source File: DrawImage.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/58606529/pdf-size-too-large-generating-through-android-pdfdocument-and-while-using-pdfbo"> * PDF size too large generating through Android PDFDocument. And while using pdfbox it is cutting image in output * </a> * <p> * This code shows how to draw an image onto a page with * the image "default size". * </p> */ @Test public void testDrawImageToFitPage() throws IOException { try ( InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")) { PDDocument document = new PDDocument(); PDImageXObject ximage = JPEGFactory.createFromStream(document,imageResource); PDPage page = new PDPage(new PDRectangle(ximage.getWidth(), ximage.getHeight())); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream.drawImage(ximage, 0, 0); contentStream.close(); document.save(new File(RESULT_FOLDER, "Willi-1.pdf")); document.close(); } }
Example 5
Source File: RotatePageContent.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java"> * Rotate PDF around its center using PDFBox in java * </a> * <p> * This test shows how to rotate the page content and then set the crop * box and media box to the bounding rectangle of the rotated page area. * </p> */ @Test public void testRotateExpandBox() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf") ) { PDDocument document = Loader.loadPDF(resource); PDPage page = document.getDocumentCatalog().getPages().get(0); PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false); Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0); cs.transform(matrix); cs.close(); PDRectangle cropBox = page.getCropBox(); Rectangle rectangle = cropBox.transform(matrix).getBounds(); PDRectangle newBox = new PDRectangle((float)rectangle.getX(), (float)rectangle.getY(), (float)rectangle.getWidth(), (float)rectangle.getHeight()); page.setCropBox(newBox); page.setMediaBox(newBox); document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-expand-box.pdf")); } }
Example 6
Source File: PdfGenerator.java From blog-tutorials with MIT License | 6 votes |
public byte[] createPdf() throws IOException { try (PDDocument document = new PDDocument()) { PDPage page = new PDPage(PDRectangle.A4); page.setRotation(90); float pageWidth = page.getMediaBox().getWidth(); float pageHeight = page.getMediaBox().getHeight(); PDPageContentStream contentStream = new PDPageContentStream(document, page); PDImageXObject chartImage = JPEGFactory.createFromImage(document, createChart((int) pageHeight, (int) pageWidth)); contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0)); contentStream.drawImage(chartImage, 0, 0); contentStream.close(); document.addPage(page); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.save(byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); } }
Example 7
Source File: PDFPage.java From Open-Lowcode with Eclipse Public License 2.0 | 6 votes |
@Override protected void print(PDDocument document) throws IOException { // create the page this.document = document; page = new PDPage(new PDRectangle(width * MM_TO_POINT, height * MM_TO_POINT)); document.addPage(page); contentStream = new PDPageContentStream(document, page); // print the widgets for (int i = 0; i < widgetstoprint.size(); i++) { PageExecutable thiswidget = widgetstoprint.get(i); thiswidget.printComponent(); } // close the page contentStream.close(); }
Example 8
Source File: VisualizeMarkedContent.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * This method outputs an XML'ish representation of the structure * tree plus text extracted for it and additionally creates a PDF * with frames representing the bounding boxes of the text inside * the structure elements. */ public void visualize(String resourceName, String resultName) throws IOException { System.out.printf("\n\n===\n%s\n===\n", resourceName); try ( InputStream resource = getClass().getResourceAsStream(resourceName)) { PDDocument document = Loader.loadPDF(resource); Map<PDPage, Map<Integer, PDMarkedContent>> markedContents = new HashMap<>(); for (PDPage page : document.getPages()) { PDFMarkedContentExtractor extractor = new PDFMarkedContentExtractor(); extractor.processPage(page); Map<Integer, PDMarkedContent> theseMarkedContents = new HashMap<>(); markedContents.put(page, theseMarkedContents); for (PDMarkedContent markedContent : extractor.getMarkedContents()) { addToMap(theseMarkedContents, markedContent); } } PDStructureNode root = document.getDocumentCatalog().getStructureTreeRoot(); Map<PDPage, PDPageContentStream> visualizations = new HashMap<>(); showStructure(document, root, markedContents, visualizations); for (PDPageContentStream canvas : visualizations.values()) canvas.close(); document.save(new File(RESULT_FOLDER, resultName)); } }
Example 9
Source File: LayerUtility.java From gcs with Mozilla Public License 2.0 | 5 votes |
/** * Places the given form over the existing content of the indicated page (like an overlay). * The form is enveloped in a marked content section to indicate that it's part of an * optional content group (OCG), here used as a layer. This optional group is returned and * can be enabled and disabled through methods on {@link PDOptionalContentProperties}. * <p> * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before calling this method to make * sure that the graphics state is reset. * * @param targetPage the target page * @param form the form to place * @param transform the transformation matrix that controls the placement of your form. You'll * need this if your page has a crop box different than the media box, or if these have negative * coordinates, or if you want to scale or adjust your form. * @param layerName the name for the layer/OCG to produce * @return the optional content group that was generated for the form usage * @throws IOException if an I/O error occurs */ public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage, PDFormXObject form, AffineTransform transform, String layerName) throws IOException { PDDocumentCatalog catalog = targetDoc.getDocumentCatalog(); PDOptionalContentProperties ocprops = catalog.getOCProperties(); if (ocprops == null) { ocprops = new PDOptionalContentProperties(); catalog.setOCProperties(ocprops); } if (ocprops.hasGroup(layerName)) { throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName); } PDRectangle cropBox = targetPage.getCropBox(); if ((cropBox.getLowerLeftX() < 0 || cropBox.getLowerLeftY() < 0) && transform.isIdentity()) { // PDFBOX-4044 LOG.warn("Negative cropBox " + cropBox + " and identity transform may make your form invisible"); } PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName); ocprops.addGroup(layer); PDPageContentStream contentStream = new PDPageContentStream( targetDoc, targetPage, AppendMode.APPEND, !DEBUG); contentStream.beginMarkedContent(COSName.OC, layer); contentStream.saveGraphicsState(); contentStream.transform(new Matrix(transform)); contentStream.drawForm(form); contentStream.restoreGraphicsState(); contentStream.endMarkedContent(); contentStream.close(); return layer; }
Example 10
Source File: JoinPages.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * @see #testJoinSmallAndBig() */ void join(PDDocument target, PDDocument topSource, PDDocument bottomSource) throws IOException { LayerUtility layerUtility = new LayerUtility(target); PDFormXObject topForm = layerUtility.importPageAsForm(topSource, 0); PDFormXObject bottomForm = layerUtility.importPageAsForm(bottomSource, 0); float height = topForm.getBBox().getHeight() + bottomForm.getBBox().getHeight(); float width, topMargin, bottomMargin; if (topForm.getBBox().getWidth() > bottomForm.getBBox().getWidth()) { width = topForm.getBBox().getWidth(); topMargin = 0; bottomMargin = (topForm.getBBox().getWidth() - bottomForm.getBBox().getWidth()) / 2; } else { width = bottomForm.getBBox().getWidth(); topMargin = (bottomForm.getBBox().getWidth() - topForm.getBBox().getWidth()) / 2; bottomMargin = 0; } PDPage targetPage = new PDPage(new PDRectangle(width, height)); target.addPage(targetPage); PDPageContentStream contentStream = new PDPageContentStream(target, targetPage); if (bottomMargin != 0) contentStream.transform(Matrix.getTranslateInstance(bottomMargin, 0)); contentStream.drawForm(bottomForm); contentStream.transform(Matrix.getTranslateInstance(topMargin - bottomMargin, bottomForm.getBBox().getHeight())); contentStream.drawForm(topForm); contentStream.close(); }
Example 11
Source File: RotatePageContent.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java"> * Rotate PDF around its center using PDFBox in java * </a> * <p> * Indeed, using the code of the OP the image mostly is rotated out of the page area. * </p> */ @Test public void testRotateLikeSagar() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf") ) { PDDocument document = Loader.loadPDF(resource); PDPage page = document.getDocumentCatalog().getPages().get(0); PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false); cs.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0)); cs.close(); document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-like-sagar.pdf")); } }
Example 12
Source File: AddImage.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/49958604/draw-image-at-mid-position-using-pdfbox-java"> * Draw image at mid position using pdfbox Java * </a> * <p> * This is a fixed version of the the OP's original code, cf. * {@link #testImageAppendLikeShanky()}. It does not mirrors the image. * </p> */ @Test public void testImageAppendNoMirror() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf"); InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg") ) { PDDocument doc = Loader.loadPDF(resource); PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi"); int w = pdImage.getWidth(); int h = pdImage.getHeight(); PDPage page = doc.getPage(0); PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true); float x_pos = page.getCropBox().getWidth(); float y_pos = page.getCropBox().getHeight(); float x_adjusted = ( x_pos - w ) / 2 + page.getCropBox().getLowerLeftX(); float y_adjusted = ( y_pos - h ) / 2 + page.getCropBox().getLowerLeftY(); contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h); contentStream.close(); doc.save(new File(RESULT_FOLDER, "test-with-image-no-mirror.pdf")); doc.close(); } }
Example 13
Source File: AddImageSaveIncremental.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** @see #testAddImagesLikeUser11465050() */ void addImageLikeUser11465050(PDDocument document, PDImageXObject image) throws IOException { PDPage page = document.getPage(0); PDRectangle pageSize = page.getMediaBox(); PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true); contentStream.drawImage(image, pageSize.getLowerLeftX(), pageSize.getLowerLeftY(), pageSize.getWidth(), pageSize.getHeight()); contentStream.close(); page.getCOSObject().setNeedToBeUpdated(true); page.getResources().getCOSObject().setNeedToBeUpdated(true); document.getDocumentCatalog().getPages().getCOSObject().setNeedToBeUpdated(true); document.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true); }
Example 14
Source File: AddImageSaveIncremental.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** @see #testAddImagesLikeUser11465050Improved() */ void addImageLikeUser11465050Improved(PDDocument document, PDImageXObject image) throws IOException { PDPage page = document.getPage(0); PDRectangle pageSize = page.getMediaBox(); PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true); contentStream.drawImage(image, pageSize.getLowerLeftX(), pageSize.getLowerLeftY(), pageSize.getWidth(), pageSize.getHeight()); contentStream.close(); page.getCOSObject().setNeedToBeUpdated(true); page.getResources().getCOSObject().setNeedToBeUpdated(true); page.getResources().getCOSObject().getCOSDictionary(COSName.XOBJECT).setNeedToBeUpdated(true); document.getDocumentCatalog().getPages().getCOSObject().setNeedToBeUpdated(true); document.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true); }
Example 15
Source File: TestEmptySignatureField.java From testarea-pdfbox2 with Apache License 2.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/37601092/pdfbox-identify-specific-pages-and-functionalities-recommendations"> * PDFBox identify specific pages and functionalities recommendations * </a> * * <p> * This test shows how to add an empty signature field with a custom appearance * to an existing PDF. * </p> */ @Test public void testAddEmptySignatureField() throws IOException { try ( InputStream sourceStream = getClass().getResourceAsStream("test.pdf"); OutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "test-with-empty-sig-field.pdf"))) { PDFont font = PDType1Font.HELVETICA; PDResources resources = new PDResources(); resources.put(COSName.getPDFName("Helv"), font); PDDocument document = Loader.loadPDF(sourceStream); PDAcroForm acroForm = new PDAcroForm(document); acroForm.setDefaultResources(resources); document.getDocumentCatalog().setAcroForm(acroForm); PDRectangle rect = new PDRectangle(50, 750, 200, 50); PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary(); PDAppearanceStream appearanceStream = new PDAppearanceStream(document); appearanceStream.setBBox(rect.createRetranslatedRectangle()); appearanceStream.setResources(resources); appearanceDictionary.setNormalAppearance(appearanceStream); PDPageContentStream contentStream = new PDPageContentStream(document, appearanceStream); contentStream.setStrokingColor(Color.BLACK); contentStream.setNonStrokingColor(Color.LIGHT_GRAY); contentStream.setLineWidth(2); contentStream.addRect(0, 0, rect.getWidth(), rect.getHeight()); contentStream.fill(); contentStream.moveTo(1 * rect.getHeight() / 4, 1 * rect.getHeight() / 4); contentStream.lineTo(2 * rect.getHeight() / 4, 3 * rect.getHeight() / 4); contentStream.moveTo(1 * rect.getHeight() / 4, 3 * rect.getHeight() / 4); contentStream.lineTo(2 * rect.getHeight() / 4, 1 * rect.getHeight() / 4); contentStream.moveTo(3 * rect.getHeight() / 4, 1 * rect.getHeight() / 4); contentStream.lineTo(rect.getWidth() - rect.getHeight() / 4, 1 * rect.getHeight() / 4); contentStream.stroke(); contentStream.setNonStrokingColor(Color.DARK_GRAY); contentStream.beginText(); contentStream.setFont(font, rect.getHeight() / 5); contentStream.newLineAtOffset(3 * rect.getHeight() / 4, -font.getBoundingBox().getLowerLeftY() * rect.getHeight() / 5000); contentStream.showText("Customer"); contentStream.endText(); contentStream.close(); PDSignatureField signatureField = new PDSignatureField(acroForm); signatureField.setPartialName("SignatureField"); PDPage page = document.getPage(0); PDAnnotationWidget widget = signatureField.getWidgets().get(0); widget.setAppearance(appearanceDictionary); widget.setRectangle(rect); widget.setPage(page); page.getAnnotations().add(widget); acroForm.getFields().add(signatureField); document.save(output); document.close(); } }
Example 16
Source File: RenderType3Character.java From testarea-pdfbox2 with Apache License 2.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox"> * Render Type3 font character as image using PDFBox * </a> * <br/> * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view"> * 4700198773.pdf * </a> * from * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble"> * extract text with custom font result non readble * </a> * <p> * This test shows how one can render individual Type 3 font glyphs as bitmaps. * Unfortunately PDFBox out-of-the-box does not provide a class to render contents * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page * with the glyph in question and render that page. * </p> * <p> * As the OP did not provide a sample PDF, we simply use one from another * stackoverflow question. There obviously might remain issues with the * OP's files. * </p> */ @Test public void testRenderSdnList() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Method PDPageContentStreamWrite = PDPageContentStream.class.getSuperclass().getDeclaredMethod("write", String.class); PDPageContentStreamWrite.setAccessible(true); try ( InputStream resource = getClass().getResourceAsStream("sdnlist.pdf")) { PDDocument document = Loader.loadPDF(resource); PDPage page = document.getPage(1); PDResources pageResources = page.getResources(); COSName f1Name = COSName.getPDFName("R144"); PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name); Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap(); COSDictionary charProcsDictionary = fontF1.getCharProcs(); for (COSName key : charProcsDictionary.keySet()) { COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key); PDType3CharProc charProc = new PDType3CharProc(fontF1, stream); PDRectangle bbox = charProc.getGlyphBBox(); if (bbox == null) bbox = charProc.getBBox(); Integer code = f1NameToCode.get(key.getName()); if (code != null) { PDDocument charDocument = new PDDocument(); PDPage charPage = new PDPage(bbox); charDocument.addPage(charPage); charPage.setResources(pageResources); PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage); charContentStream.beginText(); charContentStream.setFont(fontF1, bbox.getHeight()); //charContentStream.getOutputStream().write(String.format("<%2X> Tj\n", code).getBytes()); PDPageContentStreamWrite.invoke(charContentStream, String.format("<%2X> Tj\n", code)); charContentStream.endText(); charContentStream.close(); File result = new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.png", key.getName(), code)); PDFRenderer renderer = new PDFRenderer(charDocument); BufferedImage image = renderer.renderImageWithDPI(0, 96); ImageIO.write(image, "PNG", result); charDocument.save(new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.pdf", key.getName(), code))); charDocument.close(); } } } }
Example 17
Source File: RectanglesOverText.java From testarea-pdfbox2 with Apache License 2.0 | 4 votes |
/** * <a href="https://stackoverflow.com/questions/46080131/text-coordinates-when-stripping-from-pdfbox"> * Text coordinates when stripping from PDFBox * </a> * <br/> * <a href="https://download-a.akamaihd.net/files/media_mwb/b7/mwb_I_201711.pdf"> * mwb_I_201711.pdf * </a> * <p> * This test applies the OP's code to his example PDF file and indeed, there is an offset! * This is due to the <code>LegacyPDFStreamEngine</code> method <code>showGlyph</code> * which manipulates the text rendering matrix to make the lower left corner of the * crop box the origin. In the current version of this test, that offset is corrected, * see below. * </p> */ @Test public void testCoverTextByRectanglesMwbI201711() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("mwb_I_201711.pdf") ) { PDDocument doc = Loader.loadPDF(resource); myStripper stripper = new myStripper(); stripper.setStartPage(1); // fix it to first page just to test it stripper.setEndPage(1); stripper.getText(doc); TextLine line = stripper.lines.get(1); // the line i want to paint on float minx = -1; float maxx = -1; for (TextPosition pos: line.textPositions) { if (pos == null) continue; if (minx == -1 || pos.getTextMatrix().getTranslateX() < minx) { minx = pos.getTextMatrix().getTranslateX(); } if (maxx == -1 || pos.getTextMatrix().getTranslateX() > maxx) { maxx = pos.getTextMatrix().getTranslateX(); } } TextPosition firstPosition = line.textPositions.get(0); TextPosition lastPosition = line.textPositions.get(line.textPositions.size() - 1); // corrected x and y PDRectangle cropBox = doc.getPage(0).getCropBox(); float x = minx + cropBox.getLowerLeftX(); float y = firstPosition.getTextMatrix().getTranslateY() + cropBox.getLowerLeftY(); float w = (maxx - minx) + lastPosition.getWidth(); float h = lastPosition.getHeightDir(); PDPageContentStream contentStream = new PDPageContentStream(doc, doc.getPage(0), PDPageContentStream.AppendMode.APPEND, false, true); contentStream.setNonStrokingColor(Color.RED); contentStream.addRect(x, y, w, h); contentStream.fill(); contentStream.close(); File fileout = new File(RESULT_FOLDER, "mwb_I_201711-withRectangles.pdf"); doc.save(fileout); doc.close(); } }
Example 18
Source File: PdfManipulator.java From estatio with Apache License 2.0 | 4 votes |
private byte[] stamp( final PDDocument onePageDoc, final List<Line> leftLines, final List<Line> rightLines) throws IOException { PDPage pdPage = onePageDoc.getPage(0); final float pageHeight = pdPage.getMediaBox().getHeight(); final PDPageContentStream prependStream = new PDPageContentStream(onePageDoc, pdPage, PDPageContentStream.AppendMode.PREPEND, false); try { prependStream.transform(Matrix.getScaleInstance(SCALE_X, SCALE_Y)); prependStream.transform(Matrix.getTranslateInstance(0f, pageHeight * (1 - SCALE_Y))); } finally { prependStream.close(); } final PDPageContentStream appendStream = new PDPageContentStream(onePageDoc, pdPage, PDPageContentStream.AppendMode.APPEND, true, true); try { final int leftLineSize = leftLines.size(); final int rightLineSize = rightLines.size(); final float height = Math.max(leftLineSize, rightLineSize) * TEXT_LINE_HEIGHT + BOX_Y_PADDING; final float y = 36; float x = X_MARGIN_LEFT; float yLine = addLines(x, y, height, leftLines, appendStream); String hyperlink = leftLines.get(leftLineSize - 1).hyperlink; addHyperlink(x, yLine + TEXT_LINE_HEIGHT - 6, hyperlink, pdPage); x = X_MARGIN_RIGHT; addLines(x, y, height, rightLines, appendStream); } finally { appendStream.close(); } return asBytes(onePageDoc); }
Example 19
Source File: ReportImage.java From cat-boot with Apache License 2.0 | 3 votes |
/** * <p>Call this method to print images. <b>Make sure that the streams are closed before calling this method </b></p> * <p>Normal print method doesn't work since: http://stackoverflow.com/questions/9326245/how-to-exactly-position-an-image-inside-an-existing-pdf-page-using-pdfbox</p> * * @param document the pdDocument. * @param pageNumber page of image * @param x location of image * @param y location of image * @throws java.io.IOException in case there are problems at reading or writing the image */ public void printImage(PDDocument document, int pageNumber, float x, float y) throws IOException { PDImageXObject obj = LosslessFactory.createFromImage(document, img); PDPageContentStream currentStream = new PDPageContentStream(document, document.getDocumentCatalog().getPages().get(pageNumber), PDPageContentStream.AppendMode.APPEND, false); currentStream.drawImage(obj, x, y - height, width, height); currentStream.close(); }
Example 20
Source File: ReportElementStatic.java From cat-boot with Apache License 2.0 | 3 votes |
/** * @param document PdfBox document * @param stream IGNORED * @param pageNumber IGNORED (taken from constructor) * @param startX IGNORED (taken from constructor) * @param startY IGNORED (taken from constructor) * @param allowedWidth IGNORED (taken from constructor) * @return 0 * @throws java.io.IOException in case something happens in the underlying pdf implementation */ @Override public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException { PDPage currPage = document.getDocumentCatalog().getPages().get(pageNo); PDPageContentStream pageStream = new PDPageContentStream(document, currPage, PDPageContentStream.AppendMode.APPEND, false); base.print(document, pageStream, pageNo, x, y, width); pageStream.close(); return 0F; }