com.itextpdf.text.pdf.PdfReader Java Examples
The following examples show how to use
com.itextpdf.text.pdf.PdfReader.
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: StampColoredText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 9 votes |
/** * The OP's original code transformed into Java */ void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException { Date today = new Date(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, target); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); int tSize = 24; String mark = "DRAFT " + today; int angle = 45; float height = reader.getPageSizeWithRotation(1).getHeight()/2; float width = reader.getPageSizeWithRotation(1).getWidth()/2; PdfContentByte cb = stamper.getOverContent(1); cb.setColorFill(new BaseColor(255,200,200)); cb.setFontAndSize(bf, tSize); cb.beginText(); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.close(); }
Example #2
Source File: CreateSignature.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/30449348/signing-pdf-memory-consumption"> * Signing PDF - memory consumption * </a> * <br> * <a href="http://50mpdf.tk/50m.pdf">50m.pdf</a> * <p> * {@link #sign50MNaive()} tests the naive approach, * {@link #sign50MBruno()} tests Bruno's original approach, * {@link #sign50MBrunoPartial()} tests Bruno's approach with partial reading, * {@link #sign50MBrunoAppend()} tests Bruno's approach with append mode, and * {@link #sign50MBrunoPartialAppend()} tests Bruno's approach with partial reading and append mode. * </p> */ // runs with -Xmx240m, fails with -Xmx230m @Test public void sign50MNaive() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m-signedNaive.pdf";//50m.pdf String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "53m-signedNaive.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0',RESULT_FOLDER,true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(56, 648, 124, 780), 1, "sig2"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
Example #3
Source File: PdfDenseMergeTool.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
void merge(PdfReader reader, PdfReaderContentParser parser, int page) throws IOException { TextMarginFinder finder = parser.processContent(page, new TextMarginFinder()); Rectangle pageSizeToImport = reader.getPageSize(page); float heightToImport = finder.getHeight(); float maxHeight = pageSize.getHeight() - topMargin - bottomMargin; if (heightToImport > maxHeight) { throw new IllegalArgumentException(String.format("Page %s content too large; height: %s, limit: %s.", page, heightToImport, maxHeight)); } if (heightToImport > yPosition - pageSize.getBottom(bottomMargin)) { newPage(); } else if (!writer.isPageEmpty()) { heightToImport += gap; } yPosition -= heightToImport; PdfImportedPage importedPage = writer.getImportedPage(reader, page); writer.getDirectContent().addTemplate(importedPage, 0, yPosition - (finder.getLly() - pageSizeToImport.getBottom())); }
Example #4
Source File: ClusterCreator.java From Briss-2.0 with GNU General Public License v3.0 | 6 votes |
public static ClusterDefinition clusterPages(final File source, final PageExcludes pageExcludes) throws IOException { PdfReader reader = new PdfReader(source.getAbsolutePath()); ClusterDefinition clusters = new ClusterDefinition(); for (int page = 1; page <= reader.getNumberOfPages(); page++) { Rectangle layoutBox = getLayoutBox(reader, page); // create Cluster // if the pagenumber should be excluded then use it as a // discriminating parameter, else use default value boolean excluded = checkExclusionAndGetPageNumber(pageExcludes, page); PageCluster tmpCluster = new PageCluster(page % 2 == 0, (int) layoutBox.getWidth(), (int) layoutBox.getHeight(), excluded, page); clusters.addOrMergeCluster(tmpCluster); } reader.close(); clusters.selectAndSetPagesForMerging(); return clusters; }
Example #5
Source File: DecryptUserOnly.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/45351357/how-to-decrypt-128bit-rc4-pdf-file-in-java-with-user-password-if-it-is-encrpted"> * How to decrypt 128bit RC4 pdf file in java with user password if it is encrpted with user as well as owner password * </a> * <br/> * <a href="https://www.dropbox.com/s/pc74oox4y19awin/abc.pdf?dl=0"> * abc.pdf * </a> * <p> * This code shows how to decrypt an encrypted PDF for which you have the * user password, not the owner password. The procedure is closely related * to <a href="https://stackoverflow.com/a/27876840/1729265">Bruno's answer * here</a>. * </p> */ @Test public void testDecryptAbc() throws IOException, DocumentException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { try ( InputStream inputStream = getClass().getResourceAsStream("abc.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "abc-decrypted.pdf")) ) { PdfReader.unethicalreading = true; PdfReader reader = new PdfReader(inputStream, "abc123".getBytes()); Field encryptedField = PdfReader.class.getDeclaredField("encrypted"); encryptedField.setAccessible(true); encryptedField.set(reader, false); PdfStamper stamper = new PdfStamper(reader, outputStream); stamper.close(); reader.close(); } }
Example #6
Source File: ExtractDrawnCheckboxes.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/40549977/reading-legacy-word-forms-checkboxes-converted-to-pdf"> * Reading legacy Word forms checkboxes converted to PDF * </a> * <br> * <a href="https://www.dropbox.com/s/4z7ky3yy2yaj53i/Doc1.pdf?dl=0"> * Doc1.pdf * </a> * <p> * This test shows how one can extract the sample drawn "checkboxes" from the * sample PDF provided by the OP. * </p> */ @Test public void testExtractDoc1() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("Doc1.pdf")) { PdfReader pdfReader = new PdfReader(resource); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { System.out.printf("\nPage %s\n====\n", page); CheckBoxExtractionStrategy strategy = new CheckBoxExtractionStrategy(); PdfReaderContentParser parser = new PdfReaderContentParser(pdfReader); parser.processContent(page, strategy); for (Box box : strategy.getBoxes()) { Vector basePoint = box.getDiagonal().getStartPoint(); System.out.printf("at %s, %s - %s\n", basePoint.get(Vector.I1), basePoint.get(Vector.I2), box.isChecked() ? "checked" : "unchecked"); } } } }
Example #7
Source File: TextExtraction.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * Problems with extracting table from PDF * http://stackoverflow.com/questions/28828021/problems-with-extracting-table-from-pdf * http://www.european-athletics.org/mm/Document/EventsMeetings/General/01/27/52/10/EICH-FinalEntriesforwebsite_Neutral.pdf */ @Test public void testEichFinalEntriesForWebsiteNeutral() throws Exception { InputStream resourceStream = getClass().getResourceAsStream("EICH-FinalEntriesforwebsite_Neutral.pdf"); try { PdfReader reader = new PdfReader(resourceStream); String content = extractAndStore(reader, new File(RESULT_FOLDER, "EICH-FinalEntriesforwebsite_Neutral.%s.txt").toString()); System.out.println("\nText EICH-FinalEntriesforwebsite_Neutral.pdf\n************************"); System.out.println(content); System.out.println("************************"); } finally { if (resourceStream != null) resourceStream.close(); } }
Example #8
Source File: VerifySignature.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/48285453/verifying-certificate-of-signed-and-secured-pdf-in-itext-pdf-java"> * Verifying certificate of signed and secured PDF in iText PDF Java * </a> * <br/> * <a href="https://drive.google.com/drive/folders/1KAqHUh-Iij0I4WXJUCx-rMd8FQFq5tCe?usp=sharing"> * pdf-sample-signed.pdf * </a> * <p> * The PDF is both signed and encrypted. Apparently iText "decrypts" the * values of the <b>Contents</b> key in signature dictionaries even though * this is an explicit exception. The parsing of this "decrypted" signature * container obviously fails. * </p> */ @Test public void testVerifyPdfSampleSigned() throws IOException, GeneralSecurityException { System.out.println("\n\npdf-sample-signed.pdf\n==================="); try ( InputStream resource = getClass().getResourceAsStream("pdf-sample-signed.pdf") ) { PdfReader reader = new PdfReader(resource, "password".getBytes()); AcroFields acroFields = reader.getAcroFields(); List<String> names = acroFields.getSignatureNames(); for (String name : names) { System.out.println("Signature name: " + name); System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name)); System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions()); PdfPKCS7 pk = acroFields.verifySignature(name); System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate())); System.out.println("Document verifies: " + pk.verify()); } } System.out.println(); }
Example #9
Source File: SplitSmart.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
public List<byte[]> split(byte[] input) throws IOException, DocumentException { PdfReader pdfReader = new PdfReader(input); List<byte[]> pdfFiles = new ArrayList<>(); int pageCount = pdfReader.getNumberOfPages(); int pageIndex = 0; while (++pageIndex <= pageCount) { Document document = new Document(pdfReader.getPageSizeWithRotation(pageIndex)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PdfCopy pdfCopy = new PdfSmartCopy(document, byteArrayOutputStream); pdfCopy.setFullCompression(); PdfImportedPage pdfImportedPage = pdfCopy.getImportedPage(pdfReader, pageIndex); document.open(); pdfCopy.addPage(pdfImportedPage); document.close(); pdfCopy.close(); pdfFiles.add(byteArrayOutputStream.toByteArray()); } return pdfFiles; }
Example #10
Source File: DividerAndColorAwareTextExtraction.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/31730278/extract-text-from-pdf-between-two-dividers-with-itextsharp"> * Extract text from PDF between two dividers with ITextSharp * </a> * <br> * <a href="http://www.tjsc.jus.br/institucional/diario/a2015/20150211600.PDF"> * 20150211600.PDF * </a> * <p> * This test applies the {@link DividerAndColorAwareTextExtractionStrategy} to the OP's sample * document, page 346, to demonstrate its use. * </p> */ @Test public void test20150211600_346() throws IOException, DocumentException { InputStream resourceStream = getClass().getResourceAsStream("20150211600.PDF"); BaseColor headerColor = new CMYKColor(0.58f, 0.17f, 0, 0.56f); try { PdfReader reader = new PdfReader(resourceStream); String content = extractAndStore(reader, new File(RESULT_FOLDER, "20150211600.%s.%s.txt").toString(), 346, 346, headerColor); System.out.println("\nText 20150211600.PDF\n************************"); System.out.println(content); System.out.println("************************"); } finally { if (resourceStream != null) resourceStream.close(); } }
Example #11
Source File: TextExtraction.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/29209553/itextsharp-pdftextextractor-gettextfrompage-throwing-nullreferenceexception"> * iTextSharp PdfTextExtractor GetTextFromPage Throwing NullReferenceException * </a> * * Test using an incomplete, invalid copy of stockQuotes_03232015.pdf from * http://www.pse.com.ph/stockMarket/marketInfo-marketActivity.html?tab=4 */ @Test public void testStockQuotes_03232015_Incomplete() throws Exception { InputStream resourceStream = getClass().getResourceAsStream("stockQuotes_03232015-incomplete.pdf"); try { PdfReader reader = new PdfReader(resourceStream); String content = extractAndStore(reader, new File(RESULT_FOLDER, "stockQuotes_03232015-incomplete.%s.txt").toString()); System.out.println("\nText stockQuotes_03232015-incomplete.pdf\n************************"); System.out.println(content); System.out.println("************************"); } catch (ExceptionConverter e) { System.err.println("\nException for stockQuotes_03232015-incomplete.pdf\n************************"); e.printStackTrace(); System.err.println("************************"); } finally { if (resourceStream != null) resourceStream.close(); } }
Example #12
Source File: CreateSignature.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/30526254/sign-concatenated-pdf-in-append-mode-with-certified-no-changes-allowed"> * Sign concatenated PDF in append mode with CERTIFIED_NO_CHANGES_ALLOWED * </a> * <br> * <a href="https://www.dropbox.com/s/lea6r9fup6th44c/test_pdf.zip?dl=0">test_pdf.zip</a> * * {@link #signCertifyG()} certifies g.pdf, OK * {@link #sign2g()} merely signs 2g.pdf, OK * {@link #signCertify2gNoAppend()} certifies 2g.pdf but not in append mode, OK * {@link #tidySignCertify2g()} first tidies, then certifies 2g.pdf, OK * {@link #signCertify2g()} certifies 2g.pdf, Adobe says invalid * {@link #signCertify2gFix()} certifies 2g-fix.pdf, OK! * * 2g-fix.pdf is a patched version of 2g.pdf with a valid /Size trailer entry * and a valid, single-sectioned cross reference table */ @Test public void signCertifyG() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "g-certified.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
Example #13
Source File: PortfolioFileExtraction.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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++)); } }
Example #14
Source File: TextExtraction.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/32081406/why-is-itext-failing-to-extract-this-text"> * Why is iText failing to extract this text? * </a> * <p> * As Bruno indicated, current iText does not have an issue here. * </p> */ @Test public void testA00031() throws Exception { InputStream resourceStream = getClass().getResourceAsStream("A00031.PDF"); try { PdfReader reader = new PdfReader(resourceStream); String content = extractAndStore(reader, new File(RESULT_FOLDER, "A00031.%s.txt").toString()); System.out.println("\nText A00031.pdf\n************************"); System.out.println(content); System.out.println("************************"); } finally { if (resourceStream != null) resourceStream.close(); } }
Example #15
Source File: CreateEllipse.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); } }
Example #16
Source File: VeryDenseMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge"> * How To Remove Whitespace on Merge * </a> * <p> * Testing {@link PdfVeryDenseMergeTool} using the OP's files. * </p> */ @Test public void testMergeGrandizerFiles() throws DocumentException, IOException { try ( InputStream docA = getClass().getResourceAsStream("Header.pdf"); InputStream docB = getClass().getResourceAsStream("Body.pdf"); InputStream docC = getClass().getResourceAsStream("Footer.pdf"); ) { PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5); PdfReader readerA = new PdfReader(docA); PdfReader readerB = new PdfReader(docB); PdfReader readerC = new PdfReader(docC); try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge-veryDense.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); } } }
Example #17
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createRotatedIndirectTextPdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfReader reader = new PdfReader(createSimpleTextPdf()); PdfImportedPage template = writer.getImportedPage(reader, 1); Rectangle pageSize = reader.getPageSize(1); writer.getDirectContent().addTemplate(template, .7f, .7f, -.7f, .7f, 400, -200); document.newPage(); writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom()); document.close(); return baos.toByteArray(); }
Example #18
Source File: ComplexSignatureFields.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/32818522/itextsharp-setvisiblesignature-not-working-as-expected"> * ITextSharp SetVisibleSignature not working as expected * </a> * <p> * The issue observed by the OP (user2699460) occurs since iText(Sharp) 5.5.7 * both of iText and iTextSharp. * </p> * <p> * The file signed in this sample, test-2-user2699460-signed.pdf, has been created * as intermediary result using a simplified version of the OP's c# code. * </p> */ @Test public void signTest_2_user2699460() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/test-2-user2699460.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "test-2-user2699460-signed.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature("Bunker"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
Example #19
Source File: HideContent.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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 cover all content using a white rectangle. * </p> */ @Test public void testHideContenUnderRectangle() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-hiddenContent.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { Rectangle pageSize = pdfReader.getPageSize(page); PdfContentByte canvas = pdfStamper.getOverContent(page); canvas.setColorFill(BaseColor.WHITE); canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight()); canvas.fill(); } pdfStamper.close(); } }
Example #20
Source File: HideContent.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); } }
Example #21
Source File: TestTrimPdfPage.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
@Test public void testWithWriter() throws DocumentException, IOException { InputStream resourceStream = getClass().getResourceAsStream("test.pdf"); try { PdfReader reader = new PdfReader(resourceStream); Rectangle pageSize = reader.getPageSize(1); Rectangle rect = getOutputPageSize(pageSize, reader, 1); Document document = new Document(rect, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-writer.pdf"))); document.open(); PdfImportedPage page; // Go through all pages int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { document.newPage(); page = writer.getImportedPage(reader, i); System.out.println("BBox: "+ page.getBoundingBox().toString()); Image instance = Image.getInstance(page); document.add(instance); Rectangle outputPageSize = document.getPageSize(); System.out.println(outputPageSize.toString()); } document.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
Example #22
Source File: CreateSignature.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
@Test public void signCertify2g() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-certified.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
Example #23
Source File: VerifySignature.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/45027712/invalid-signature-when-signing-an-existing-sigrature-field-with-cosign-sapi"> * Invalid signature when signing an existing sigrature field with CoSign SAPI * </a> * <br/> * <a href="https://www.dropbox.com/s/j6eme53lleaok13/test_signed.pdf?dl=0"> * test_signed-1.pdf * </a> * <p> * Validation shows verification success while both Adobe and SD DSS fail. * Embedded certificates have issues (emailAddress RDN is typed PrintableString * which is wrong - specified is IA5String - and does not even make sense as * there is no '@' in PrintableString), but does this explain it? * </p> */ @Test public void testVerifyTestSigned1() throws IOException, GeneralSecurityException { System.out.println("\n\ntest_signed-1.pdf\n==================="); try ( InputStream resource = getClass().getResourceAsStream("test_signed-1.pdf") ) { PdfReader reader = new PdfReader(resource); AcroFields acroFields = reader.getAcroFields(); List<String> names = acroFields.getSignatureNames(); for (String name : names) { System.out.println("Signature name: " + name); System.out.println("Signature covers whole document: " + acroFields.signatureCoversWholeDocument(name)); System.out.println("Document revision: " + acroFields.getRevision(name) + " of " + acroFields.getTotalRevisions()); PdfPKCS7 pk = acroFields.verifySignature(name); System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate())); System.out.println("Document verifies: " + pk.verify()); } } System.out.println(); }
Example #24
Source File: TextExtraction.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/37919301/itext-textextracting-example-not-working"> * itext: Textextracting example not working * </a> * <br/> * <a href="http://s000.tinyupload.com/index.php?file_id=04085076377229572360"> * HTR_Reichsgericht.pdf * </a> * <p> * The issue cannot be reproduced. Analyzing the given stacktrace one is led to assume the * OP uses the number of a non-existing page. * </p> */ @Test public void testHTR_Reichsgericht() throws IOException, DocumentException { InputStream resourceStream = getClass().getResourceAsStream("HTR_Reichsgericht.pdf"); try { PdfReader reader = new PdfReader(resourceStream); String content = extractAndStoreSimple(reader, new File(RESULT_FOLDER, "HTR_Reichsgericht.%s.txt").toString()); System.out.println("\nText HTR_Reichsgericht.pdf\n************************"); System.out.println(content); System.out.println("************************"); } finally { if (resourceStream != null) resourceStream.close(); } }
Example #25
Source File: SwitchPageCanvas.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); } }
Example #26
Source File: MarkContent.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/50121297/missing-colored-area-on-pdf-using-itext-pdf"> * Missing colored area on pdf using itext pdf * </a> * <p> * This test shows how to mark a whole table row without the * marking hiding the existing content or vice versa. * </p> */ @Test public void test() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-marked.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(pdfReader, result); PdfContentByte canvas = stamper.getOverContent(1); canvas.saveState(); PdfGState state = new PdfGState(); state.setBlendMode(new PdfName("Multiply")); canvas.setGState(state); canvas.setColorFill(BaseColor.YELLOW); canvas.rectangle(60, 586, 477, 24); canvas.fill(); canvas.restoreState(); stamper.close(); } }
Example #27
Source File: RedactText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/44304695/itext-5-5-11-bold-text-looks-blurry-after-using-pdfcleanupprocessor"> * iText 5.5.11 - bold text looks blurry after using PdfCleanUpProcessor * </a> * <br/> * <a href="http://s000.tinyupload.com/index.php?file_id=52420782334200922303"> * before.pdf * </a> * <p> * Indeed, the observation by the OP can be reproduced. The issue has been introduced * into iText in commits d5abd23 and 9967627, both dated May 4th, 2015. * </p> */ @Test public void testRedactLikeTieco() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("before.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "before-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(0f, 0f, 595f, 680f))); PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
Example #28
Source File: ExtractCertifiedSchoolList.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
@Test public void testCertifiedSchoolList_9_16_2015() throws IOException { try ( Writer data = new OutputStreamWriter(new FileOutputStream(new File(RESULT_FOLDER, "data.txt")), "UTF-8"); Writer nonData = new OutputStreamWriter(new FileOutputStream(new File(RESULT_FOLDER, "non-data.txt")), "UTF-8"); InputStream resource = getClass().getResourceAsStream("certified-school-list-9-16-2015.pdf") ) { CertifiedSchoolListExtractionStrategy strategy = new CertifiedSchoolListExtractionStrategy(data, nonData); PdfReader reader = new PdfReader(resource); PdfReaderContentParser parser = new PdfReaderContentParser(reader); for (int page = 1; page <= reader.getNumberOfPages(); page++) parser.processContent(page, strategy); // parser.processContent(28, strategy); strategy.close(); } }
Example #29
Source File: PDFExtract.java From pdf-extract with GNU General Public License v3.0 | 6 votes |
private void setAccessPermissions(PdfReader reader, AtomicReference<DocumentObject> refDoc) { DocumentObject doc = refDoc.get(); // PdfReader.unethicalreading = true; int permissions = (int) reader.getPermissions(); // doc.permission.isEncrytped = reader.isEncrypted(); doc.permission.canAssembly = PdfEncryptor.isAssemblyAllowed(permissions); doc.permission.canCopy = PdfEncryptor.isCopyAllowed(permissions); doc.permission.canPrint = PdfEncryptor.isPrintingAllowed(permissions); doc.permission.canPrintDegraded = PdfEncryptor.isDegradedPrintingAllowed(permissions); doc.permission.canModified = PdfEncryptor.isModifyContentsAllowed(permissions); doc.permission.canModifyAnnotations = PdfEncryptor.isModifyAnnotationsAllowed(permissions); doc.permission.canFillInForm = PdfEncryptor.isFillInAllowed(permissions); doc.permission.canScreenReader = PdfEncryptor.isScreenReadersAllowed(permissions); doc.permission.verbose = PdfEncryptor.getPermissionsVerbose(permissions); }
Example #30
Source File: SignableDocumentBehavior.java From CounterSign with GNU Affero General Public License v3.0 | 5 votes |
/** * When the "signable" aspect is applied, extract the signature fields and add them * to the multivalue property */ public void onAddAspect(NodeRef nodeRef, QName aspectTypeQName) { try { // when the aspect is added, extract the signature fields from the PDF ArrayList<String> signatureFields = new ArrayList<String>(); ContentReader pdfReader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); AcroFields form = reader.getAcroFields(); Map<String, Item> fields = form.getFields(); Iterator<String> it = fields.keySet().iterator(); while(it.hasNext()) { String fieldName = it.next(); if(form.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) { // add this signature field to the list of available fields signatureFields.add(fieldName); } } serviceRegistry.getNodeService().setProperty(nodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, signatureFields); } catch(IOException ex) { logger.error("Error extracting PDF signature fields from document: " + ex); } }