Java Code Examples for com.itextpdf.text.pdf.PdfReader#close()
The following examples show how to use
com.itextpdf.text.pdf.PdfReader#close() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: 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: PDF2WordExample.java From tutorials with MIT License | 6 votes |
private static void generateDocFromPDF(String filename) throws IOException { XWPFDocument doc = new XWPFDocument(); String pdf = filename; PdfReader reader = new PdfReader(pdf); PdfReaderContentParser parser = new PdfReaderContentParser(reader); for (int i = 1; i <= reader.getNumberOfPages(); i++) { TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); String text = strategy.getResultantText(); XWPFParagraph p = doc.createParagraph(); XWPFRun run = p.createRun(); run.setText(text); run.addBreak(BreakType.PAGE); } FileOutputStream out = new FileOutputStream("src/output/pdf.docx"); doc.write(out); out.close(); reader.close(); doc.close(); }
Example 3
Source File: DenseMerging.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 PdfDenseMergeTool} 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"); ) { PdfDenseMergeTool tool = new PdfDenseMergeTool(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.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); } } }
Example 4
Source File: ScriptCounterSignService.java From CounterSign with GNU Affero General Public License v3.0 | 6 votes |
/** * Gets the page count for a PDF document * * @param nodeRef * @return */ public int getPageCount(String nodeRef){ try { ContentReader reader = serviceRegistry .getContentService().getReader(new NodeRef(nodeRef), ContentModel.PROP_CONTENT); PdfReader pdfReader = new PdfReader(reader.getContentInputStream()); int count = pdfReader.getNumberOfPages(); pdfReader.close(); return count; } catch(IOException ioex) { return -1; } }
Example 5
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 6
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 7
Source File: CreateEllipse.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 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 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(); } }
Example 8
Source File: CropManager.java From Briss-2.0 with GNU General Public License v3.0 | 5 votes |
public static CropJob createCropJob(ClusterJob curClusterJob) throws IOException { File source = curClusterJob.getSource(); if (source != null && source.exists()) { PdfReader reader = new PdfReader(source.getAbsolutePath()); CropJob result = new CropJob(source, reader.getNumberOfPages(), reader.getInfo(), SimpleBookmark.getBookmark(reader)); reader.close(); result.setClusterCollection(curClusterJob.getClusterCollection()); return result; } return null; }
Example 9
Source File: VeryDenseMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 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}. * </p> */ @Test public void testMergeOnlyGraphics() throws DocumentException, IOException { byte[] docA = createSimpleCircleGraphicsPdf(20, 20, 20); Files.write(new File(RESULT_FOLDER, "circlesOnlyA.pdf").toPath(), docA); byte[] docB = createSimpleCircleGraphicsPdf(50, 10, 2); Files.write(new File(RESULT_FOLDER, "circlesOnlyB.pdf").toPath(), docB); byte[] docC = createSimpleCircleGraphicsPdf(100, -20, 3); Files.write(new File(RESULT_FOLDER, "circlesOnlyC.pdf").toPath(), docC); byte[] docD = createSimpleCircleGraphicsPdf(20, 20, 20); Files.write(new File(RESULT_FOLDER, "circlesOnlyD.pdf").toPath(), docD); PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5); PdfReader readerA = new PdfReader(docA); PdfReader readerB = new PdfReader(docB); PdfReader readerC = new PdfReader(docC); PdfReader readerD = new PdfReader(docD); try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "circlesOnlyMerge-veryDense.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); readerD.close(); } }
Example 10
Source File: DenseMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/27988503/how-can-i-combine-multiple-pdf-files-excluding-page-breaks-using-itextsharp"> * How can I combine multiple PDF files excluding page breaks using iTextSharp? * </a> * <p> * Testing {@link PdfDenseMergeTool}. * </p> */ @Test public void testMergeOnlyText() throws DocumentException, IOException { byte[] docA = createSimpleTextPdf("First document, paragraph %s.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyA.pdf").toPath(), docA); byte[] docB = createSimpleTextPdf("Second document, paragraph %s.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyB.pdf").toPath(), docB); byte[] docC = createSimpleTextPdf("Third document, paragraph %s, a bit longer lines.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyC.pdf").toPath(), docC); byte[] docD = createSimpleTextPdf("Fourth document, paragraph %s, let us make this a much longer paragraph spanning more than one line.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyD.pdf").toPath(), docD); PdfDenseMergeTool tool = new PdfDenseMergeTool(PageSize.A4, 18, 18, 5); PdfReader readerA = new PdfReader(docA); PdfReader readerB = new PdfReader(docB); PdfReader readerC = new PdfReader(docC); PdfReader readerD = new PdfReader(docD); try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "textOnlyMerge.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); readerD.close(); } }
Example 11
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
static byte[] cleanUp(byte[] source, List<PdfCleanUpLocation> cleanUpLocations) throws IOException, DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, baos); PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); return baos.toByteArray(); }
Example 12
Source File: CropManager.java From Briss-2.0 with GNU General Public License v3.0 | 5 votes |
public static CropJob createCropJob(File source) throws IOException { CropJob result = null; if (source != null && source.exists()) { PdfReader reader = new PdfReader(source.getAbsolutePath()); result = new CropJob(source, reader.getNumberOfPages(), reader.getInfo(), SimpleBookmark.getBookmark(reader)); reader.close(); return result; } return result; }
Example 13
Source File: DocumentCropper.java From Briss-2.0 with GNU General Public License v3.0 | 5 votes |
public PdfMetaInformation(final File source) throws IOException { PdfReader reader = new PdfReader(source.getAbsolutePath()); this.sourcePageCount = reader.getNumberOfPages(); this.sourceMetaInfo = reader.getInfo(); this.sourceBookmarks = SimpleBookmark.getBookmark(reader); reader.close(); }
Example 14
Source File: VeryDenseMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 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}. * </p> */ @Test public void testMergeOnlyText() throws DocumentException, IOException { byte[] docA = createSimpleTextPdf("First document, paragraph %s.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyA.pdf").toPath(), docA); byte[] docB = createSimpleTextPdf("Second document, paragraph %s.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyB.pdf").toPath(), docB); byte[] docC = createSimpleTextPdf("Third document, paragraph %s, a bit longer lines.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyC.pdf").toPath(), docC); byte[] docD = createSimpleTextPdf("Fourth document, paragraph %s, let us make this a much longer paragraph spanning more than one line.", 3); Files.write(new File(RESULT_FOLDER, "textOnlyD.pdf").toPath(), docD); PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5); PdfReader readerA = new PdfReader(docA); PdfReader readerB = new PdfReader(docB); PdfReader readerC = new PdfReader(docC); PdfReader readerD = new PdfReader(docD); try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "textOnlyMerge-veryDense.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC, readerD); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); readerD.close(); } }
Example 15
Source File: ImportPageWithoutFreeSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/31980979/itext-importing-styled-text-and-informations-from-an-existing-pdf"> * iText: Importing styled Text and informations from an existing PDF * </a> * <p> * This method demonstrates how to import merely the region of a PDF page with * actual content. The main necessity is to call {@link #cropPdf(PdfReader)} * for the reader in question which restricts the media boxes of the pages to * the bounding box of the existing content. * </p> */ @Test public void testImportPages() throws DocumentException, IOException { byte[] docText = createSimpleTextPdf(); Files.write(new File(RESULT_FOLDER, "textOnly.pdf").toPath(), docText); byte[] docGraphics = createSimpleCircleGraphicsPdf(); Files.write(new File(RESULT_FOLDER, "graphicsOnly.pdf").toPath(), docGraphics); PdfReader readerText = new PdfReader(docText); cropPdf(readerText); PdfReader readerGraphics = new PdfReader(docGraphics); cropPdf(readerGraphics); try ( FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "importPages.pdf"))) { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, fos); document.open(); document.add(new Paragraph("Let's import 'textOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD))); document.add(Image.getInstance(writer.getImportedPage(readerText, 1))); document.add(new Paragraph("and now 'graphicsOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD))); document.add(Image.getInstance(writer.getImportedPage(readerGraphics, 1))); document.add(new Paragraph("That's all, folks!", new Font(FontFamily.HELVETICA, 12, Font.BOLD))); document.close(); } finally { readerText.close(); readerGraphics.close(); } }
Example 16
Source File: Merging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <a href="https://stackoverflow.com/questions/46120706/when-i-open-a-pdf-in-adobe-acrobat-pro-dc-the-text-is-getting-messed-up-for-pdf"> * when i open a pdf in adobe acrobat pro Dc the text is getting messed up for pdf creation i used itext5.5.12 * </a> * <p> * Test files "1 Loyds.pdf", "2 CRPWLI.pdf", "3 SLC Dec.pdf", "4 Schedule.pdf", * and "5 Sched of INS.pdf" were received via e-mail from Kishore Rachakonda * ([email protected]) on 2017-09-11 17:31. * </p> * <p> * This test is a port of the Ruby-on-Rails merge routine provided by the OP. * The result does not have the problem described by the OP. * </p> * <p> * Later it became clear that the OP's merge result was post-processed by at * least two other programs, and one of those post processors appears to have * optimized the use of embedded fonts. Unfortunately "5 Sched of INS.pdf" is * not a completely valid PDF: It uses an embedded subset of a font but does * not mark the font name accordingly. Thus, the optimizing post processor * added this mere font subset (assuming it to be the whole font program) to * font resources which require glyphs missing in the subset. * </p> */ @Test public void testMergeLikeKishoreSagar() throws IOException, DocumentException { try ( InputStream resource1 = getClass().getResourceAsStream("1 Loyds.pdf"); InputStream resource2 = getClass().getResourceAsStream("2 CRPWLI.pdf"); InputStream resource3 = getClass().getResourceAsStream("3 SLC Dec.pdf"); InputStream resource4 = getClass().getResourceAsStream("4 Schedule.pdf"); InputStream resource5 = getClass().getResourceAsStream("5 Sched of INS.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "mergeLikeKishoreSagar.pdf"))) { InputStream[] pdf_files = {resource1, resource2, resource3, resource4, resource5}; Document doc = new Document(); PdfCopy pdf_copy = new PdfCopy(doc, result); doc.open(); for (InputStream pdf : pdf_files) { PdfReader reader = new PdfReader(pdf); int pages = reader.getNumberOfPages(); for (int p = 1; p <= pages; p++) pdf_copy.addPage(pdf_copy.getImportedPage(reader, p)); reader.close(); } doc.close(); } /* ported from the original: doc =Document.new pdf_copy = PdfCopy.new(doc, FileStream.new(@output_filename)) doc.open @pdf_files.each do |pdf| reader = PdfReader.new(pdf) pages = reader.getNumberOfPages() (1..pages).each do |p| pdf_copy.addPage(pdf_copy.getImportedPage(reader, p)) end reader.close end doc.close */ }
Example 17
Source File: DocumentCropper.java From Briss-2.0 with GNU General Public License v3.0 | 4 votes |
private static void cropMultipliedFile(final CropDefinition cropDefinition, final File multipliedDocument, final PdfMetaInformation pdfMetaInformation) throws DocumentException, IOException { PdfReader reader = new PdfReader(multipliedDocument.getAbsolutePath()); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(cropDefinition.getDestinationFile())); stamper.setMoreInfo(pdfMetaInformation.getSourceMetaInfo()); PdfDictionary pageDict; int newPageNumber = 1; for (int sourcePageNumber = 1; sourcePageNumber <= pdfMetaInformation.getSourcePageCount(); sourcePageNumber++) { List<Float[]> rectangleList = cropDefinition.getRectanglesForPage(sourcePageNumber); // if no crop was selected do nothing if (rectangleList.isEmpty()) { newPageNumber++; continue; } for (Float[] ratios : rectangleList) { 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 = RectangleHandler.calculateScaledRectangle(boxes, ratios, rotation); PdfArray scaleBoxArray = createScaledBoxArray(scaledBox); 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] = pdfMetaInformation.getSourcePageCount() + (newPageNumber - sourcePageNumber); SimpleBookmark.shiftPageNumbers(pdfMetaInformation.getSourceBookmarks(), rectangleList.size() - 1, range); } stamper.setOutlines(pdfMetaInformation.getSourceBookmarks()); stamper.close(); reader.close(); }
Example 18
Source File: RedactText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/43211367/getting-exception-while-redacting-pdf-using-itext"> * getting exception while redacting pdf using itext * </a> * <br/> * <a href="https://drive.google.com/file/d/0B-zalNTEeIOwM1JJVWctcW8ydU0/view?usp=drivesdk"> * edited_120192824_5 (1).pdf * </a> * <p> * Indeed, the PdfClean classes throw a {@link NullPointerException} on page * 1 of this PDF. As it turns out, the cause is that the PDF makes use of a * construct which according to the PDF specification is obsolete and iText, * therefore, chose not to support. * </p> */ @Test public void testRedactLikeDevAvitesh() throws DocumentException, IOException { // InputStream resource = new FileInputStream("D:/itext/edited_120192824_5 (1).pdf"); // OutputStream result = new FileOutputStream(new File(OUTPUTDIR, // "aviteshs.pdf")); try ( InputStream resource = getClass().getResourceAsStream("edited_120192824_5 (1).pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "edited_120192824_5 (1)-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); int pageCount = reader.getNumberOfPages(); Rectangle linkLocation1 = new Rectangle(440f, 700f, 470f, 710f); Rectangle linkLocation2 = new Rectangle(308f, 205f, 338f, 215f); Rectangle linkLocation3 = new Rectangle(90f, 155f, 130f, 165f); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); for (int currentPage = 1; currentPage <= pageCount; currentPage++) { if (currentPage == 1) { cleanUpLocations.add(new PdfCleanUpLocation(currentPage, linkLocation1, BaseColor.BLACK)); cleanUpLocations.add(new PdfCleanUpLocation(currentPage, linkLocation2, BaseColor.BLACK)); cleanUpLocations.add(new PdfCleanUpLocation(currentPage, linkLocation3, BaseColor.BLACK)); } else { cleanUpLocations.add(new PdfCleanUpLocation(currentPage, linkLocation1, BaseColor.BLACK)); } } PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); try { cleaner.cleanUp(); } catch (Exception e) { e.printStackTrace(); } stamper.close(); reader.close(); } }
Example 19
Source File: WatermarkPdfTests.java From kbase-doc with Apache License 2.0 | 4 votes |
/** * pdf 用图片加水印 * @author eko.zhan at 2018年9月2日 下午1:44:58 * @throws FileNotFoundException * @throws IOException * @throws DocumentException */ @Test public void testVisioAsPdfWithImg() throws FileNotFoundException, IOException, DocumentException{ File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx"); File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf"); if (!outputFile.exists()) { convert(inputFile, outputFile); } File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf"); final String IMG = "D:\\Xiaoi\\logo\\logo.png"; //转换成 pdf 后利用 itext 加水印 PdfReader reader = new PdfReader(new FileInputStream(outputFile)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile)); int pageNo = reader.getNumberOfPages(); // text watermark Font f = new Font(FontFamily.HELVETICA, 30); Phrase p = new Phrase("Xiaoi Robot Image", f); // image watermark Image img = Image.getInstance(IMG); float w = img.getScaledWidth(); float h = img.getScaledHeight(); // transparency PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0.5f); // properties PdfContentByte over; Rectangle pagesize; float x, y; // loop over every page for (int i = 1; i <= pageNo; i++) { pagesize = reader.getPageSizeWithRotation(i); x = (pagesize.getLeft() + pagesize.getRight()) / 2; y = (pagesize.getTop() + pagesize.getBottom()) / 2; over = stamper.getOverContent(i); over.saveState(); over.setGState(gs1); if (i % 2 == 1) ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0); else over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2)); over.restoreState(); } stamper.close(); reader.close(); }
Example 20
Source File: RedactText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/38605538/itextpdf-redaction-partly-redacted-text-string-is-fully-removed"> * itextpdf Redaction :Partly redacted text string is fully removed * </a> * <br/> * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVMDc4MnE5VmU5YVk/view"> * Document.pdf * </a> * <p> * This test applies the redaction using the {@link StrictPdfCleanUpProcessor} * which in contrast to the {@link PdfCleanUpProcessor} causes only text to be * removed if it is <b>completely</b> inside the redaction zone . The original * removes also text located merely <b>partially</b> inside the redaction zone. * Furthermore this test uses a larger redaction zone to check whether text * completely contained in the redaction zone really is removed. * </p> * <p> * This might more correspond to what the OP desires. * </p> * @see #testRedactLikeMayankPandey() * @see #testRedactStrictForMayankPandey() */ @Test public void testRedactStrictForMayankPandeyLarge() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("Document.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Document-redacted-strict-large.pdf")) ) { PdfReader reader = new PdfReader(resource); StrictPdfCleanUpProcessor cleaner= null; PdfStamper stamper = new PdfStamper(reader, result); stamper.setRotateContents(false); List<mkl.testarea.itext5.pdfcleanup.PdfCleanUpLocation> cleanUpLocations = new ArrayList<>(); Rectangle rectangle = new Rectangle(380, 640, 430, 680); cleanUpLocations.add(new mkl.testarea.itext5.pdfcleanup.PdfCleanUpLocation(1, rectangle, BaseColor.BLACK)); cleaner = new StrictPdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }