/** * <a href="http://stackoverflow.com/questions/34394199/i-cant-rotate-my-page-from-existing-pdf"> * I can't rotate my page from existing PDF * </a> * <p> * Switching between portrait and landscape like this obviously will cut off some parts of the page. * </p> */ @Test public void testSwitchOrientation() throws DocumentException, IOException { try (InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/n2013.00849449.pdf")) { PdfReader reader = new PdfReader(resourceStream); int n = reader.getNumberOfPages(); PdfDictionary pageDict; for (int i = 1; i <= n; i++) { Rectangle rect = reader.getPageSize(i); Rectangle crop = reader.getCropBox(i); pageDict = reader.getPageN(i); pageDict.put(PdfName.MEDIABOX, new PdfArray(new float[] {rect.getBottom(), rect.getLeft(), rect.getTop(), rect.getRight()})); pageDict.put(PdfName.CROPBOX, new PdfArray(new float[] {crop.getBottom(), crop.getLeft(), crop.getTop(), crop.getRight()})); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "n2013.00849449-switch.pdf"))); stamper.close(); reader.close(); } }
public byte[] buildSignedPDF(String digestOID, byte[] signature, byte[] hash) throws Exception { byte[] hashTmp = null; if (dateTime != null) hashTmp = hash; byte[] pkcs7enc = PKCS7Manager.buildPDFPKCS7(digestOID, x509Certificate, signature, hashTmp, dateTime); PdfDictionary dic = new PdfDictionary(); PdfString contents = new PdfString(pkcs7enc).setHexWriting(true); contentsSize = contents.length(); dic.put(PdfName.CONTENTS, contents); sap.close(dic); return bout.toByteArray(); }
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; }
@Override protected void write(PdfContentStreamProcessor processor, PdfLiteral operator, List<PdfObject> operands) throws IOException { String operatorString = operator.toString(); if ("gs".equals(operatorString)) { updateTransparencyFrom((PdfName) operands.get(0)); } PdfLiteral[] mapping = operatorMapping.get(operatorString); if (mapping != null) { int index = 0; if (strokingAlpha < 1) index |= 1; if (nonStrokingAlpha < 1) index |= 2; operator = mapping[index]; operands.set(operands.size() - 1, operator); } super.write(processor, operator, operands); }
@Test public void testOPCode() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 ); PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT; PdfAnnotation linkRed = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" ); PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" ); BaseColor baseColorRed = new BaseColor(255,0,0); BaseColor baseColorGreen = new BaseColor(0,255,0); linkRed.setColor(baseColorRed); linkGreen.setColor(baseColorGreen); double angleDegrees = 10; double angleRadians = Math.PI*angleDegrees/180; stamper.addAnnotation(linkRed, 1); linkGreen.applyCTM(AffineTransform.getRotateInstance(angleRadians)); stamper.addAnnotation(linkGreen, 1); 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 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(); } }
/** * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer"> * Filling a PDF with iTextsharp and then hiding the base layer * </a> * <p> * This test shows how to remove all content. * </p> */ @Test public void testRemoveContent() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-removedContent.pdf"))) { PdfReader pdfReader = new PdfReader(resource); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { PdfDictionary pageDictionary = pdfReader.getPageN(page); pageDictionary.remove(PdfName.CONTENTS); } new PdfStamper(pdfReader, result).close(); } }
/** * These two methods ({@link #extractAttachments(PdfReader, String)} and * {@link #extractAttachment(PdfReader, File, PdfString, PdfDictionary)}) * essentially are the OP's original code posted in his question. They * extract files without the folder structure. */ public static void extractAttachments(PdfReader reader, String dir) throws IOException { File folder = new File(dir); folder.mkdirs(); PdfDictionary root = reader.getCatalog(); PdfDictionary names = root.getAsDict(PdfName.NAMES); System.out.println("" + names.getKeys().toString()); PdfDictionary embedded = names.getAsDict(PdfName.EMBEDDEDFILES); System.out.println("" + embedded.toString()); PdfArray filespecs = embedded.getAsArray(PdfName.NAMES); //System.out.println(filespecs.getAsString(root1)); for (int i = 0; i < filespecs.size();) { extractAttachment(reader, folder, filespecs.getAsString(i++), filespecs.getAsDict(i++)); } }
/** * <p> * These two methods ({@link #extractAttachmentsWithFolders(PdfReader, String)} and * {@link #extractAttachment(PdfReader, Map, PdfString, PdfDictionary)}) extend the * functionality of the OP's original code posted in his question. They extract files * with the folder structure. * </p> * <p> * The information concerning the portfolio folder structure is retrieved using * the method {@link #retrieveFolders(PdfReader, File)} and its helper method * {@link #collectFolders(Map, PdfDictionary, File)}. * </p> */ public static void extractAttachmentsWithFolders(PdfReader reader, String dir) throws IOException, DocumentException { File folder = new File(dir); folder.mkdirs(); Map<Integer, File> folders = retrieveFolders(reader, folder); PdfDictionary root = reader.getCatalog(); PdfDictionary names = root.getAsDict(PdfName.NAMES); System.out.println("" + names.getKeys().toString()); PdfDictionary embedded = names.getAsDict(PdfName.EMBEDDEDFILES); System.out.println("" + embedded.toString()); PdfArray filespecs = embedded.getAsArray(PdfName.NAMES); for (int i = 0; i < filespecs.size();) { extractAttachment(reader, folders, folder, filespecs.getAsString(i++), filespecs.getAsDict(i++)); } }
static Map<Integer, File> retrieveFolders(PdfReader reader, File baseDir) throws DocumentException { Map<Integer, File> result = new HashMap<Integer, File>(); PdfDictionary root = reader.getCatalog(); PdfDictionary collection = root.getAsDict(PdfName.COLLECTION); if (collection == null) throw new DocumentException("Document has no Collection dictionary"); PdfDictionary folders = collection.getAsDict(FOLDERS); if (folders == null) throw new DocumentException("Document collection has no folders dictionary"); collectFolders(result, folders, baseDir); return result; }
/** * * @param parameters * @return a map of preferences with corresponding value to be set on the documents */ private Map<PdfName, PdfObject> getConfiguredViewerPreferencesMap(ViewerPreferencesParameters parameters) { Map<PdfName, PdfObject> confPreferences = new HashMap<PdfName, PdfObject>(); if (parameters.getDirection() != null) { confPreferences.put(PdfName.DIRECTION, ViewerPreferencesUtils.getDirection(parameters.getDirection())); } if (parameters.getDuplex() != null) { confPreferences.put(PdfName.DUPLEX, ViewerPreferencesUtils.getDuplex(parameters.getDuplex())); } if (parameters.getPrintScaling() != null) { confPreferences.put(PdfName.PRINTSCALING, ViewerPreferencesUtils.getPrintScaling(parameters.getPrintScaling())); } confPreferences.put(PdfName.NONFULLSCREENPAGEMODE, ViewerPreferencesUtils.getNFSMode(parameters.getNfsMode())); Set<PdfBooleanPreference> activePref = parameters.getEnabledPreferences(); for (PdfBooleanPreference boolPref : PdfBooleanPreference.values()) { if (activePref.contains(boolPref)) { confPreferences.put(ViewerPreferencesUtils.getBooleanPreference(boolPref), PdfBoolean.PDFTRUE); } else { confPreferences.put(ViewerPreferencesUtils.getBooleanPreference(boolPref), PdfBoolean.PDFFALSE); } } return confPreferences; }
private void unpack(Set<PdfDictionary> dictionaries) throws TaskIOException { for (PdfDictionary dictionary : dictionaries) { PdfName type = dictionary.getAsName(PdfName.TYPE); if (PdfName.F.equals(type) || PdfName.FILESPEC.equals(type)) { PdfDictionary ef = dictionary.getAsDict(PdfName.EF); PdfString fn = dictionary.getAsString(PdfName.F); if (fn != null && ef != null) { PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F)); if (prs != null) { File tmpFile = copyToTemporaryFile(prs); outputWriter.addOutput(file(tmpFile).name(fn.toUnicodeString())); } } } } }
private void doExecute() throws TaskException, IOException { when(context.getTask(parameters)).thenReturn((Task) victimTask); victim.execute(parameters); PdfReader reader = getReaderFromResultStream("test_file.pdf"); assertCreator(reader); assertEquals(PdfVersion.VERSION_1_7.getVersionAsCharacter(), reader.getPdfVersion()); PdfDictionary catalog = PdfViewerPreferencesImp.getViewerPreferences(reader.getCatalog()) .getViewerPreferences(); assertEquals(PdfName.SIMPLEX, catalog.getAsName(PdfName.DUPLEX)); assertEquals(PdfName.L2R, catalog.getAsName(PdfName.DIRECTION)); assertEquals(PdfName.APPDEFAULT, catalog.getAsName(PdfName.PRINTSCALING)); assertEquals(PdfName.USETHUMBS, catalog.getAsName(PdfName.NONFULLSCREENPAGEMODE)); assertEquals(PdfBoolean.PDFTRUE, catalog.getAsBoolean(PdfName.CENTERWINDOW)); assertEquals(PdfBoolean.PDFTRUE, catalog.getAsBoolean(PdfName.HIDEMENUBAR)); assertEquals(PdfBoolean.PDFFALSE, catalog.getAsBoolean(PdfName.HIDETOOLBAR)); reader.close(); }
/** * Extracts text from a PDF document. * * @param src the original PDF document * @throws java.io.IOException */ public List<Page> extractText(InputStream src) throws IOException { List<Page> pages = Lists.newArrayList(); PdfReader reader = new PdfReader(src); RenderListener listener = new InternalListener(); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener); for (int i = 1; i <= reader.getNumberOfPages(); i++) { pages.add(currentPage = new Page()); PdfDictionary pageDic = reader.getPageN(i); PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES); processor.processContent(ContentByteUtils.getContentBytesForPage(reader, i), resourcesDic); } reader.close(); return pages; }
public PdfName getLevelPdfName() { int level = getLevel(); switch (level) { case 0: return PdfName.H1; case 1: return PdfName.H2; case 2: return PdfName.H3; case 3: return PdfName.H4; case 4: return PdfName.H5; case 5: return PdfName.H6; default: return PdfName.H; } }
@Override public void convertToXml(PdfReader reader, OutputStream os, String charset) throws IOException { this.reader = reader; OutputStreamWriter outs = new OutputStreamWriter(os, charset); out = new PrintWriter(outs); out.println("<Document>"); // get the StructTreeRoot from the root object PdfDictionary catalog = reader.getCatalog(); PdfDictionary struct = catalog.getAsDict(PdfName.STRUCTTREEROOT); roleMap = struct.getAsDict(PdfName.ROLEMAP); if (struct == null) throw new IOException(MessageLocalization.getComposedMessage("no.structtreeroot.found")); // Inspect the child or children of the StructTreeRoot inspectChild(struct.getDirectObject(PdfName.K)); out.println("</Document>"); out.flush(); out.close(); }
@SuppressWarnings("deprecation") public void preClose() throws Exception { if (dateTime != null) sap.setSignDate(StringUtils.dateToCalendar(dateTime)); sap.setAcro6Layers(false); sap.setCertificate(x509Certificate); //sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ETSI_CADES_DETACHED); // PdfName.ADBE_PKCS7_DETACHED if (dateTime != null) dic.setDate(new PdfDate(sap.getSignDate())); dic.setName(X509Utils.getCN(x509Certificate)); dic.setCert(x509Certificate.getEncoded()); sap.setCryptoDictionary(dic); /* * PdfDictionary dic = new PdfDictionary(); * dic.put(PdfName.FT, PdfName.SIG); * dic.put(PdfName.FILTER, PdfName.ADOBE_PPKMS); * dic.put(PdfName.SUBFILTER, PdfName.ETSI_CADES_DETACHED); * dic.put(PdfName.M, new PdfDate(sap.getSignDate())); * dic.put(PdfName.NAME, new PdfString(Utils.getCN(cert))); * sap.setCryptoDictionary(dic); */ HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2)); sap.preClose(exc); dataToSign = IOUtils.toByteArray(sap.getRangeStream()); }
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(); } }
/** * This method edits the immediate contents of a page, i.e. its content stream. * It explicitly does not descent into form xobjects, patterns, or annotations. */ public void editPage(PdfStamper pdfStamper, int pageNum) throws IOException { PdfReader pdfReader = pdfStamper.getReader(); PdfDictionary page = pdfReader.getPageN(pageNum); byte[] pageContentInput = ContentByteUtils.getContentBytesForPage(pdfReader, pageNum); page.remove(PdfName.CONTENTS); editContent(pageContentInput, page.getAsDict(PdfName.RESOURCES), pdfStamper.getUnderContent(pageNum)); }
SignatureData(/*ContentInfo contentInfo,*/ byte[] signatureContainer, byte[] rawContents, PdfName subFilter, Date signingTime) { //this.contentInfo = contentInfo; this.signatureContainer = signatureContainer; this.rawContents = rawContents; this.subFilter = subFilter; this.signingTime = signingTime; }
@Override public void renderText(TextRenderInfo renderInfo) { DocumentFont font =renderInfo.getFont(); PdfDictionary dict = font.getFontDictionary(); PdfDictionary encoding = dict.getAsDict(PdfName.ENCODING); PdfArray diffs = encoding.getAsArray(PdfName.DIFFERENCES); ; StringBuilder builder = new StringBuilder(); for (byte b : renderInfo.getPdfString().getBytes()) { PdfName name = diffs.getAsName((char)b); String s = name.toString().substring(2); int i = Integer.parseUnsignedInt(s, 16); builder.append((char)i); } try { stringField.set(renderInfo, builder.toString()); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } strategy.renderText(renderInfo); }
/** * <p> * A primitive attempt at copying links from page <code>sourcePage</code> * of <code>PdfReader reader</code> to page <code>targetPage</code> of * <code>PdfStamper stamper</code>. * </p> * <p> * This method is meant only for the use case at hand, i.e. copying a link * to an external URI without expecting any advanced features. * </p> */ void copyLinks(PdfStamper stamper, int targetPage, PdfReader reader, int sourcePage) { PdfDictionary sourcePageDict = reader.getPageNRelease(sourcePage); PdfArray annotations = sourcePageDict.getAsArray(PdfName.ANNOTS); if (annotations != null && annotations.size() > 0) { for (PdfObject annotationObject : annotations) { annotationObject = PdfReader.getPdfObject(annotationObject); if (!annotationObject.isDictionary()) continue; PdfDictionary annotation = (PdfDictionary) annotationObject; if (!PdfName.LINK.equals(annotation.getAsName(PdfName.SUBTYPE))) continue; PdfArray rectArray = annotation.getAsArray(PdfName.RECT); if (rectArray == null || rectArray.size() < 4) continue; Rectangle rectangle = PdfReader.getNormalizedRectangle(rectArray); PdfName hightLight = annotation.getAsName(PdfName.H); if (hightLight == null) hightLight = PdfAnnotation.HIGHLIGHT_INVERT; PdfDictionary actionDict = annotation.getAsDict(PdfName.A); if (actionDict == null || !PdfName.URI.equals(actionDict.getAsName(PdfName.S))) continue; PdfString urlPdfString = actionDict.getAsString(PdfName.URI); if (urlPdfString == null) continue; PdfAction action = new PdfAction(urlPdfString.toString()); PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(), rectangle, hightLight, action); stamper.addAnnotation(link, targetPage); } } }
/** * <a href="https://stackoverflow.com/questions/46642994/how-to-create-pdf-package-using-pdfbox"> * How to create pdf package using PdfBox? * </a> * <p> * This test executes the OP's code to determine the changes applied by * it to the PDF. * </p> */ @Test public void test() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf"); OutputStream out = new FileOutputStream(new File(RESULT_FOLDER, "test-collection.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(pdfReader, out); stamper.makePackage(PdfName.T); stamper.close(); } }
void show(FdfReader fdfReader) { PdfDictionary catalog = fdfReader.getCatalog(); catalog = catalog.getAsDict(PdfName.FDF); Assert.assertNotNull("FDF catalogue is null", catalog); PdfArray annots = catalog.getAsArray(PdfName.ANNOTS); Assert.assertNotNull("FDF annotations are null", annots); System.out.println(annots); }
/** * <a href="http://stackoverflow.com/questions/31402602/how-to-rename-only-the-first-found-duplicate-acrofield-in-pdf"> * How to rename only the first found duplicate acrofield in pdf? * </a> * <br> * <a href="http://s000.tinyupload.com/index.php?file_id=34970992934525199618"> * test_duplicate_field2.pdf * </a> * <p> * Demonstration of how to transform generate a new field for a widget. * </p> */ @Test public void testWidgetToField() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("test_duplicate_field2.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test_duplicate_field2-widgetToField.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfDictionary form = reader.getCatalog().getAsDict(PdfName.ACROFORM); PdfArray fields = form.getAsArray(PdfName.FIELDS); for (PdfObject object: fields) { PdfDictionary field = (PdfDictionary) PdfReader.getPdfObject(object); if ("Text1".equals(field.getAsString(PdfName.T).toString())) { PdfDictionary newField = new PdfDictionary(); PRIndirectReference newFieldRef = reader.addPdfObject(newField); fields.add(newFieldRef); newField.putAll(field); newField.put(PdfName.T, new PdfString("foobar")); PdfArray newKids = new PdfArray(); newField.put(PdfName.KIDS, newKids); PdfArray kids = field.getAsArray(PdfName.KIDS); PdfObject widget = kids.remove(0); newKids.add(widget); PdfDictionary widgetDict = (PdfDictionary) PdfReader.getPdfObject(widget); widgetDict.put(PdfName.PARENT, newFieldRef); break; } } PdfStamper stamper = new PdfStamper(reader, result); stamper.close(); } }
/** * <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(); } }
@Test public void testOwnAppearances() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate-app.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); BaseColor baseColorRed = new BaseColor(255,0,0); BaseColor baseColorGreen = new BaseColor(0,255,0); Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 ); PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT; PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" ); PdfTemplate appearance = PdfTemplate.createTemplate(stamper.getWriter(), linkLocation.getWidth(), linkLocation.getHeight()); appearance.setColorFill(baseColorGreen); appearance.rectangle(0, 0, linkLocation.getWidth(), linkLocation.getHeight()); appearance.fill(); double angleDegrees = 35; double angleRadians = Math.PI*angleDegrees/180; AffineTransform at = AffineTransform.getRotateInstance(angleRadians); appearance.setMatrix((float)at.getScaleX(), (float)at.getShearY(),(float) at.getShearX(), (float)at.getScaleY(),(float) at.getTranslateX(), (float)at.getTranslateY()); linkGreen.setAppearance(PdfName.N, appearance); linkGreen.setColor(baseColorGreen); stamper.addAnnotation(linkGreen, 1); PdfAnnotation linkRed = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" ); linkRed.setColor(baseColorRed); stamper.addAnnotation(linkRed, 1); 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(); } }
@Test public void testWithStamper() throws DocumentException, IOException { InputStream resourceStream = getClass().getResourceAsStream("test.pdf"); try { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper.pdf"))); // Go through all pages int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { Rectangle pageSize = reader.getPageSize(i); Rectangle rect = getOutputPageSize(pageSize, reader, i); PdfDictionary page = reader.getPageN(i); page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()})); stamper.markUsed(page); } stamper.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
@Test public void testWithStamperTopBottom() throws DocumentException, IOException { InputStream resourceStream = getClass().getResourceAsStream("test.pdf"); try { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper-top-bottom.pdf"))); // Go through all pages int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { Rectangle pageSize = reader.getPageSize(i); Rectangle rect = getOutputPageSize2(pageSize, reader, i); PdfDictionary page = reader.getPageN(i); page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()})); stamper.markUsed(page); } stamper.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
@Test public void testWithStamperCentered() throws DocumentException, IOException { InputStream resourceStream = getClass().getResourceAsStream("test.pdf"); try { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper-centered.pdf"))); // Go through all pages int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { Rectangle pageSize = reader.getPageSize(i); Rectangle rect = getOutputPageSize3(pageSize, reader, i); PdfDictionary page = reader.getPageN(i); page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()})); stamper.markUsed(page); } stamper.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
@Test public void testWithStamperExtFinder() throws DocumentException, IOException { InputStream resourceStream = getClass().getResourceAsStream("test.pdf"); try { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-stamper-ext.pdf"))); // Go through all pages int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { Rectangle pageSize = reader.getPageSize(i); Rectangle rect = getOutputPageSize4(pageSize, reader, i); PdfDictionary page = reader.getPageN(i); page.put(PdfName.CROPBOX, new PdfArray(new float[]{rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop()})); stamper.markUsed(page); } stamper.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
/** * This methods creates a copy of the source document containing each page twice, * once with the cropbox limited to the left half page, once to the right one. */ void splitIntoHalfPages(InputStream source, File target) throws IOException, DocumentException { final PdfReader reader = new PdfReader(source); try ( OutputStream targetStream = new FileOutputStream(target) ) { Document document = new Document(); PdfCopy copy = new PdfCopy(document, targetStream); document.open(); for (int page = 1; page <= reader.getNumberOfPages(); page++) { PdfDictionary pageN = reader.getPageN(page); Rectangle cropBox = reader.getCropBox(page); PdfArray leftBox = new PdfArray(new float[]{cropBox.getLeft(), cropBox.getBottom(), (cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getTop()}); PdfArray rightBox = new PdfArray(new float[]{(cropBox.getLeft() + cropBox.getRight()) / 2.0f, cropBox.getBottom(), cropBox.getRight(), cropBox.getTop()}); PdfImportedPage importedPage = copy.getImportedPage(reader, page); pageN.put(PdfName.CROPBOX, leftBox); copy.addPage(importedPage); pageN.put(PdfName.CROPBOX, rightBox); copy.addPage(importedPage); } document.close(); } finally { reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/37027579/how-to-associate-a-previous-signature-in-a-new-signature-field"> * How to associate a previous signature in a new signature field * </a> * <br/> * <span>BLANK-signed.pdf, <em>a blank file from elsewhere with an invisible signature.</em></span> * <p> * Quite surprisingly it turns out that changing the signature appearance is possible without * breaking the signature, merely a warning appears which can be hidden by simply signing again. * </p> */ @Test public void testChangeAppearances() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("BLANK-signed.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "BLANK-signed-app.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result, '\0', true); AcroFields acroFields = pdfStamper.getAcroFields(); for (String signatureName : acroFields.getSignatureNames()) { Item field = acroFields.getFieldItem(signatureName); field.writeToAll(PdfName.RECT, new PdfArray(new int[]{100,100,200,200}), Item.WRITE_WIDGET); field.markUsed(acroFields, Item.WRITE_WIDGET); PdfAppearance appearance = PdfAppearance.createAppearance(pdfStamper.getWriter(), 100, 100); appearance.setColorStroke(BaseColor.RED); appearance.moveTo(0, 0); appearance.lineTo(99, 99); appearance.moveTo(0, 99); appearance.lineTo(99, 0); appearance.stroke(); PdfDictionary appDict = new PdfDictionary(); appDict.put(PdfName.N, appearance.getIndirectReference()); field.writeToAll(PdfName.AP, appDict, Item.WRITE_WIDGET); } pdfStamper.close(); } }
/** * This method checks the signatures referenced from the AcroForm Fields. */ void verify(PdfReader reader) throws GeneralSecurityException { PdfDictionary top = (PdfDictionary)PdfReader.getPdfObjectRelease(reader.getCatalog().get(PdfName.ACROFORM)); if (top == null) { System.out.println("No AcroForm, so nothing to verify"); return; } PdfArray arrfds = (PdfArray)PdfReader.getPdfObjectRelease(top.get(PdfName.FIELDS)); if (arrfds == null || arrfds.isEmpty()) { System.out.println("No AcroForm Fields, so nothing to verify"); return; } for (PdfObject object : arrfds) { object = PdfReader.getPdfObject(object); if (object == null) { System.out.println("* A null entry."); } else if (!object.isDictionary()) { System.out.println("* A non-dictionary entry."); } else { verify(reader, (PdfDictionary) object, null, null, null, false); } } }
/** * <a href="http://stackoverflow.com/questions/41949253/how-to-add-columntext-as-an-annotation-in-itext-pdf"> * How to add columnText as an annotation in itext pdf * </a> * <p> * This test demonstrates how to use a columntext in combination with an annotation. * </p> */ @Test public void testAddAnnotationLikeJasonY() throws IOException, DocumentException { String html ="<html><h1>Header</h1><p>A paragraph</p><p>Another Paragraph</p></html>"; String css = "h1 {color: red;}"; ElementList elementsList = XMLWorkerHelper.parseToElementList(html, css); try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "JasonY.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); Rectangle cropBox = reader.getCropBox(1); PdfAnnotation annotation = stamper.getWriter().createAnnotation(cropBox, PdfName.FREETEXT); PdfAppearance appearance = PdfAppearance.createAppearance(stamper.getWriter(), cropBox.getWidth(), cropBox.getHeight()); ColumnText ct = new ColumnText(appearance); ct.setSimpleColumn(new Rectangle(cropBox.getWidth(), cropBox.getHeight())); elementsList.forEach(element -> ct.addElement(element)); ct.go(); annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/37748346/extract-text-with-itext-not-works-encoding-or-crypted-text"> * Extract text with iText not works: encoding or crypted text? * </a> * <br/> * <a href="https://dl.dropboxusercontent.com/u/6413030/pb.pdf"> * pb.pdf * </a> * <p> * The document has not been provided by the OP but by * <a href="http://stackoverflow.com/users/1127485/sschuberth">sschuberth</a> * in a comment. * </p> * <p> * In contrast to {@link #testPb()}, we here first remove the <b>ToUnicode</b> * tables of the fonts. And indeed, now extraction succeeds. * </p> */ @Test public void testPbNoToUnicode() throws Exception { InputStream resourceStream = getClass().getResourceAsStream("pb.pdf"); try { PdfReader reader = new PdfReader(resourceStream); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfDictionary pageResources = reader.getPageResources(i); if (pageResources == null) continue; PdfDictionary pageFonts = pageResources.getAsDict(PdfName.FONT); if (pageFonts == null) continue; for (PdfName key : pageFonts.getKeys()) { PdfDictionary fontDictionary = pageFonts.getAsDict(key); fontDictionary.put(PdfName.TOUNICODE, null); } } String content = extractAndStore(reader, new File(RESULT_FOLDER, "pb-noToUnicode.%s.txt").toString()); System.out.println("\nText pb.pdf without ToUnicode\n************************"); System.out.println(content); System.out.println("************************"); } finally { if (resourceStream != null) resourceStream.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); }