private int numberOfVisibleSignatureFieldsOnSignaturePage(AcroFields readerFields, ArrayList<String> signatureFieldsNames, int signaturePage) { int count = 0; for (String signatureFieldName : signatureFieldsNames) { Item i = readerFields.getFieldItem(signatureFieldName); int page = i.getPage(0); if(page == signaturePage){ PdfDictionary pdct = i.getMerged(0); PdfNumber flags = pdct.getAsNumber(PdfName.F); if ((flags.intValue() & PdfAnnotation.FLAGS_HIDDEN) == 0) { count = count + 1; } } } return count; }
/** * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t"> * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5 * </a> * <p> * This test creates an ellipse annotation without appearance on a page with rotation. * The ellipse form looks ok but it is moved to the right of the actual appearance rectangle when viewed in Adobe Reader. * This is caused by iText creating a non-standard rectangle, the lower left not being the lower left etc. * </p> * @see #testCreateEllipse() * @see #testCreateEllipseAppearance() * @see #testCreateEllipseAppearanceOnRotated() * @see #testCreateCorrectEllipseAppearanceOnRotated() */ @Test public void testCreateEllipseOnRotated() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90)); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150); PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false); annotation.setFlags(PdfAnnotation.FLAGS_PRINT); annotation.setColor(BaseColor.RED); annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID)); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
void updateTransparencyFrom(PdfName gsName) { PdfDictionary extGState = getGraphicsStateDictionary(gsName); if (extGState != null) { PdfNumber number = extGState.getAsNumber(PdfName.ca); if (number != null) nonStrokingAlpha = number.floatValue(); number = extGState.getAsNumber(PdfName.CA); if (number != null) strokingAlpha = number.floatValue(); } }
/** * <a href="http://stackoverflow.com/questions/37275267/how-to-make-pdf-annotation-as-read-only-using-itext"> * how to make pdf annotation as read only using itext? * </a> * <br/> * test-annotated.pdf <i>simple PDF with sticky note</i> * * <p> * This test shows how to set the read-only flags of all annotations of a document. * </p> */ @Test public void testMarkAnnotationsReadOnly() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("test-annotated.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "test-annotated-ro.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); for (int page = 1; page <= reader.getNumberOfPages(); page++) { PdfDictionary pageDictionary = reader.getPageN(page); PdfArray annotationArray = pageDictionary.getAsArray(PdfName.ANNOTS); if (annotationArray == null) continue; for (PdfObject object : annotationArray) { PdfObject directObject = PdfReader.getPdfObject(object); if (directObject instanceof PdfDictionary) { PdfDictionary annotationDictionary = (PdfDictionary) directObject; PdfNumber flagsNumber = annotationDictionary.getAsNumber(PdfName.F); int flags = flagsNumber != null ? flagsNumber.intValue() : 0; flags |= PdfAnnotation.FLAGS_READONLY; annotationDictionary.put(PdfName.F, new PdfNumber(flags)); } } } stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t"> * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5 * </a> * <p> * This test creates an ellipse annotation with appearance on a page with rotation. * The ellipse position looks ok but it is deformed. * This is caused by iText rotating the annotation rectangle but not (how could it?) the appearance rectangle. * </p> * @see #testCreateEllipse() * @see #testCreateEllipseAppearance() * @see #testCreateEllipseOnRotated() * @see #testCreateCorrectEllipseAppearanceOnRotated() */ @Test public void testCreateEllipseAppearanceOnRotated() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse-appearance.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90)); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150); PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false); annotation.setFlags(PdfAnnotation.FLAGS_PRINT); annotation.setColor(BaseColor.RED); annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID)); PdfContentByte cb = stamper.getOverContent(1); PdfAppearance app = cb.createAppearance(rect.getWidth(), rect.getHeight()); app.setColorStroke(BaseColor.RED); app.setLineWidth(3.5); app.ellipse( 1.5, 1.5, rect.getWidth() - 1.5, rect.getHeight() - 1.5); app.stroke(); annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t"> * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5 * </a> * <p> * This test creates an ellipse annotation with appearance with switched dimensions on a page with rotation. * Everything looks ok. * </p> * @see #testCreateEllipse() * @see #testCreateEllipseAppearance() * @see #testCreateEllipseOnRotated() * @see #testCreateEllipseAppearanceOnRotated() */ @Test public void testCreateCorrectEllipseAppearanceOnRotated() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse-appearance-correct.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90)); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150); PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false); annotation.setFlags(PdfAnnotation.FLAGS_PRINT); annotation.setColor(BaseColor.RED); annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID)); PdfContentByte cb = stamper.getOverContent(1); PdfAppearance app = cb.createAppearance(rect.getHeight(), rect.getWidth()); app.setColorStroke(BaseColor.RED); app.setLineWidth(3.5); app.ellipse( 1.5, 1.5, rect.getHeight() - 1.5, rect.getWidth() - 1.5); app.stroke(); annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
static void collectFolders(Map<Integer, File> collection, PdfDictionary folder, File baseDir) { PdfString name = folder.getAsString(PdfName.NAME); File folderDir = new File(baseDir, name.toString()); folderDir.mkdirs(); PdfNumber id = folder.getAsNumber(PdfName.ID); collection.put(id.intValue(), folderDir); PdfDictionary next = folder.getAsDict(PdfName.NEXT); if (next != null) collectFolders(collection, next, baseDir); PdfDictionary child = folder.getAsDict(CHILD); if (child != null) collectFolders(collection, child, folderDir); }
private static PdfArray createScaledBoxArray(final Rectangle scaledBox) { PdfArray scaleBoxArray = new PdfArray(); scaleBoxArray.add(new PdfNumber(scaledBox.getLeft())); scaleBoxArray.add(new PdfNumber(scaledBox.getBottom())); scaleBoxArray.add(new PdfNumber(scaledBox.getRight())); scaleBoxArray.add(new PdfNumber(scaledBox.getTop())); return scaleBoxArray; }
/** * <a href="http://stackoverflow.com/questions/28911509/how-to-retain-page-labels-when-concatenating-an-existing-pdf-with-a-pdf-created"> * How to retain page labels when concatenating an existing pdf with a pdf created from scratch? * </a> * <p> * A proposal how to implement the task using a {@link PdfStamper}. */ @Test public void testInsertTitlePage() throws IOException, DocumentException { try ( InputStream documentStream = getClass().getResourceAsStream("Labels.pdf"); InputStream titleStream = getClass().getResourceAsStream("Cover.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "labels-with-cover-page.pdf")) ) { PdfReader titleReader = new PdfReader(titleStream); PdfReader reader = new PdfReader(documentStream); PdfStamper stamper = new PdfStamper(reader, outputStream); PdfImportedPage page = stamper.getImportedPage(titleReader, 1); stamper.insertPage(1, titleReader.getPageSize(1)); PdfContentByte content = stamper.getUnderContent(1); content.addTemplate(page, 0, 0); copyLinks(stamper, 1, titleReader, 1); PdfDictionary root = reader.getCatalog(); PdfDictionary labels = root.getAsDict(PdfName.PAGELABELS); if (labels != null) { PdfArray newNums = new PdfArray(); newNums.add(new PdfNumber(0)); PdfDictionary coverDict = new PdfDictionary(); coverDict.put(PdfName.P, new PdfString("Cover Page")); newNums.add(coverDict); PdfArray nums = labels.getAsArray(PdfName.NUMS); if (nums != null) { for (int i = 0; i < nums.size() - 1; ) { int n = nums.getAsNumber(i++).intValue(); newNums.add(new PdfNumber(n+1)); newNums.add(nums.getPdfObject(i++)); } } labels.put(PdfName.NUMS, newNums); stamper.markUsed(labels); } stamper.close(); } }
@Override protected void configurePDFWriter(PdfWriter writer) throws IOException { double leftMap = pageFormat.getPageLeft(); double bottomMap = pageFormat.getPageBottom(); PdfDictionary lgiDict = new PdfDictionary(new PdfName("LGIDict")); lgiDict.put(new PdfName("Version"), new PdfNumber("2.1")); /* // Registration (optional): not interpreted by GDAL double rightMap = pageFormat.getPageRight(); double topMap = pageFormat.getPageTop(); float leftPage = xToPagePx((float) leftMap); float bottomPage = yToPagePx((float) bottomMap); float rightPage = xToPagePx((float) rightMap); float topPage = yToPagePx((float) topMap); PdfArray lowerLeftPoint = new PdfArray(); lowerLeftPoint.add(new PdfString(Double.toString(leftPage))); lowerLeftPoint.add(new PdfString(Double.toString(bottomPage))); lowerLeftPoint.add(new PdfString(Double.toString(leftMap))); lowerLeftPoint.add(new PdfString(Double.toString(bottomMap))); PdfArray upperRightPoint = new PdfArray(); upperRightPoint.add(new PdfString(Double.toString(rightPage))); upperRightPoint.add(new PdfString(Double.toString(topPage))); upperRightPoint.add(new PdfString(Double.toString(rightMap))); upperRightPoint.add(new PdfString(Double.toString(topMap))); PdfArray registration = new PdfArray(); registration.add(lowerLeftPoint); registration.add(upperRightPoint); lgiDict.put(new PdfName("Registration"), registration); */ // FIXME usage of PageFormat.MM2PX double scale = pageFormat.getPageWidthWorldCoordinates() / pageFormat.getPageWidth() / PageFormat.MM2PX; PdfArray ctmArray = new PdfArray(); ctmArray.add(new PdfString(Double.toString(scale))); ctmArray.add(new PdfString("0")); ctmArray.add(new PdfString("0")); ctmArray.add(new PdfString(Double.toString(scale))); ctmArray.add(new PdfString(Double.toString(leftMap))); ctmArray.add(new PdfString(Double.toString(bottomMap))); lgiDict.put(new PdfName("CTM"), ctmArray); // Projection PdfDictionary projectionDict = new PdfDictionary(new PdfName("Projection")); projectionDict.put(new PdfName("ProjectionType"), new PdfString("NONE")); lgiDict.put(new PdfName("Projection"), projectionDict); /* // Neatline (optional) PdfArray neatlinePoints = new PdfArray(); neatlinePoints.add(new PdfString(Double.toString(leftPage))); neatlinePoints.add(new PdfString(Double.toString(bottomPage))); neatlinePoints.add(new PdfString(Double.toString(rightPage))); neatlinePoints.add(new PdfString(Double.toString(topPage))); lgiDict.put(new PdfName("Neatline"), neatlinePoints); */ writer.addPageDictEntry(new PdfName("LGIDict"), lgiDict); }
private static void cropMultipliedFile(File source, CropJob cropJob) throws FileNotFoundException, DocumentException, IOException { PdfReader reader = new PdfReader(source.getAbsolutePath()); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(cropJob.getDestinationFile())); stamper.setMoreInfo(cropJob.getSourceMetaInfo()); PdfDictionary pageDict; int newPageNumber = 1; for (int origPageNumber = 1; origPageNumber <= cropJob.getSourcePageCount(); origPageNumber++) { SingleCluster cluster = cropJob.getClusterCollection().getSingleCluster(origPageNumber); // if no crop was selected do nothing if (cluster.getRatiosList().size() == 0) { newPageNumber++; continue; } for (Float[] ratios : cluster.getRatiosList()) { pageDict = reader.getPageN(newPageNumber); List<Rectangle> boxes = new ArrayList<Rectangle>(); boxes.add(reader.getBoxSize(newPageNumber, "media")); boxes.add(reader.getBoxSize(newPageNumber, "crop")); int rotation = reader.getPageRotation(newPageNumber); Rectangle scaledBox = calculateScaledRectangle(boxes, ratios, rotation); PdfArray scaleBoxArray = new PdfArray(); scaleBoxArray.add(new PdfNumber(scaledBox.getLeft())); scaleBoxArray.add(new PdfNumber(scaledBox.getBottom())); scaleBoxArray.add(new PdfNumber(scaledBox.getRight())); scaleBoxArray.add(new PdfNumber(scaledBox.getTop())); pageDict.put(PdfName.CROPBOX, scaleBoxArray); pageDict.put(PdfName.MEDIABOX, scaleBoxArray); // increment the pagenumber newPageNumber++; } int[] range = new int[2]; range[0] = newPageNumber - 1; range[1] = cropJob.getSourcePageCount() + (newPageNumber - origPageNumber); SimpleBookmark.shiftPageNumbers(cropJob.getSourceBookmarks(), cluster.getRatiosList().size() - 1, range); } stamper.setOutlines(cropJob.getSourceBookmarks()); stamper.close(); reader.close(); }
/** * apply the rotation to the given page if necessary * * @param pageNmber */ private void apply(int pageNmber) { PdfDictionary dictionary = reader.getPageN(pageNmber); dictionary.put(PdfName.ROTATE, new PdfNumber(rotation.addRotation(getRotation(reader.getPageRotation(pageNmber))).getDegrees())); }
@Override public void exportElement(JRPdfExporterContext exporterContext, JRGenericPrintElement element) { try { PdfWriter writer = exporterContext.getPdfWriter(); PdfIndirectObject swfRef; boolean newContext = !existingContexts.containsKey(exporterContext); if (newContext) { PdfDictionary extensions = new PdfDictionary(); PdfDictionary adobeExtension = new PdfDictionary(); adobeExtension.put(new PdfName("BaseVersion"), PdfWriter.PDF_VERSION_1_7); adobeExtension.put(new PdfName("ExtensionLevel"), new PdfNumber(3)); extensions.put(new PdfName("ADBE"), adobeExtension); writer.getExtraCatalog().put(new PdfName("Extensions"), extensions); byte[] swfData = getChartSwf(); PdfFileSpecification swfFile = PdfFileSpecification.fileEmbedded(writer, null, "Open Flash Chart", swfData); swfRef = writer.addToBody(swfFile); existingContexts.put(exporterContext, swfRef); } else { swfRef = (PdfIndirectObject) existingContexts.get(exporterContext); } Rectangle rect = new Rectangle(element.getX() + exporterContext.getOffsetX(), exporterContext.getExportedReport().getPageHeight() - element.getY() - exporterContext.getOffsetY(), element.getX() + exporterContext.getOffsetX() + element.getWidth(), exporterContext.getExportedReport().getPageHeight() - element.getY() - exporterContext.getOffsetY() - element.getHeight()); PdfAnnotation ann = new PdfAnnotation(writer, rect); ann.put(PdfName.SUBTYPE, new PdfName("RichMedia")); PdfDictionary settings = new PdfDictionary(); PdfDictionary activation = new PdfDictionary(); activation.put(new PdfName("Condition"), new PdfName("PV")); settings.put(new PdfName("Activation"), activation); ann.put(new PdfName("RichMediaSettings"), settings); PdfDictionary content = new PdfDictionary(); HashMap<String, PdfIndirectReference> assets = new HashMap<String, PdfIndirectReference>(); assets.put("map.swf", swfRef.getIndirectReference()); PdfDictionary assetsDictionary = PdfNameTree.writeTree(assets, writer); content.put(new PdfName("Assets"), assetsDictionary); PdfArray configurations = new PdfArray(); PdfDictionary configuration = new PdfDictionary(); PdfArray instances = new PdfArray(); PdfDictionary instance = new PdfDictionary(); instance.put(new PdfName("Subtype"), new PdfName("Flash")); PdfDictionary params = new PdfDictionary(); String chartData = ((ChartGenerator) element.getParameterValue(ChartGenerator.PARAMETER_CHART_GENERATOR)).generateChart(); String vars = "inline_data=" + chartData; params.put(new PdfName("FlashVars"), new PdfString(vars)); instance.put(new PdfName("Params"), params); instance.put(new PdfName("Asset"), swfRef.getIndirectReference()); PdfIndirectObject instanceRef = writer.addToBody(instance); instances.add(instanceRef.getIndirectReference()); configuration.put(new PdfName("Instances"), instances); PdfIndirectObject configurationRef = writer.addToBody(configuration); configurations.add(configurationRef.getIndirectReference()); content.put(new PdfName("Configurations"), configurations); ann.put(new PdfName("RichMediaContent"), content); writer.addAnnotation(ann); } catch (Exception e) { throw new RuntimeException(e); } }