Java Code Examples for com.itextpdf.text.pdf.PdfStamper#getOverContent()
The following examples show how to use
com.itextpdf.text.pdf.PdfStamper#getOverContent() .
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: StampColoredText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 7 votes |
/** * The OP's code transformed into Java changed with the work-around. */ void stampTextChanged(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.setFontAndSize(bf, tSize); cb.beginText(); cb.setColorFill(new BaseColor(255,200,200)); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.close(); }
Example 3
Source File: PDFUtil.java From roncoo-education with MIT License | 7 votes |
/** * 水印 */ public static void setWatermark(MultipartFile src, File dest, String waterMarkName, int permission) throws DocumentException, IOException { PdfReader reader = new PdfReader(src.getInputStream()); PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(dest))); int total = reader.getNumberOfPages() + 1; PdfContentByte content; BaseFont base = BaseFont.createFont(); for (int i = 1; i < total; i++) { content = stamper.getOverContent(i);// 在内容上方加水印 content.beginText(); content.setTextMatrix(70, 200); content.setFontAndSize(base, 30); content.setColorFill(BaseColor.GRAY); content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 400, 45); content.endText(); } stamper.close(); }
Example 4
Source File: StampUnicodeText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader. With a different starting file, though, it doesn't, cf. * {@link #testAddUnicodeStampEg_01()}. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
Example 5
Source File: StampUnicodeText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With * a different starting file, though, it doesn't as this test shows. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampEg_01() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("eg_01.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
Example 6
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 7
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 8
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 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(); } }
Example 9
Source File: WatermarkPdfTests.java From kbase-doc with Apache License 2.0 | 5 votes |
/** * pdf 用文字加水印,存在问题,如何支持中文 * @author eko.zhan at 2018年9月2日 下午1:44:40 * @throws FileNotFoundException * @throws IOException * @throws DocumentException */ @Test public void testVisioAsPdfWithText() 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"); //转换成 pdf 后利用 itext 加水印 PdfReader reader = new PdfReader(new FileInputStream(outputFile)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile)); int pageNo = reader.getNumberOfPages(); Font f = new Font(FontFamily.HELVETICA, 28); Phrase p = new Phrase("Xiaoi Robot", f); for (int i=1;i<=pageNo;i++) { PdfContentByte over = stamper.getOverContent(i); over.saveState(); PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0.5f); over.setGState(gs1); ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 297, 450, 0); over.restoreState(); } stamper.close(); reader.close(); }
Example 10
Source File: FindFreeSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
void testExt(String resource, float minWidth, float minHeight) throws IOException, DocumentException { String name = new File(resource).getName(); String target = String.format("%s-freeSpaceExt%.0fx%.0f.pdf", name, minWidth, minHeight); InputStream resourceStream = getClass().getResourceAsStream(resource); try { PdfReader reader = new PdfReader(resourceStream); System.out.printf("\nFree %.0fx%.0f regions in %s\n", minWidth, minHeight, name); Collection<Rectangle2D> rectangles = findExt(reader, minWidth, minHeight, 1); print(rectangles); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, target))); PdfContentByte over = stamper.getOverContent(1); enhance(over, rectangles); Point2D[] points = getPointsOfInterest(reader.getCropBox(1)); for (int i = 0; i < points.length; i++) enhance(over, rectangles, points[i], colors[i]); stamper.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
Example 11
Source File: FindFreeSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
void test(String resource, float minWidth, float minHeight) throws IOException, DocumentException { String name = new File(resource).getName(); String target = String.format("%s-freeSpace%.0fx%.0f.pdf", name, minWidth, minHeight); InputStream resourceStream = getClass().getResourceAsStream(resource); try { PdfReader reader = new PdfReader(resourceStream); System.out.printf("\nFree %.0fx%.0f regions in %s\n", minWidth, minHeight, name); Collection<Rectangle2D> rectangles = find(reader, minWidth, minHeight, 1); print(rectangles); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, target))); PdfContentByte over = stamper.getOverContent(1); enhance(over, rectangles); Point2D[] points = getPointsOfInterest(reader.getCropBox(1)); for (int i = 0; i < points.length; i++) enhance(over, rectangles, points[i], colors[i]); stamper.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
Example 12
Source File: TextLocationExtraction.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
void mark(InputStream input, OutputStream output, Pattern pattern) throws DocumentException, IOException { PdfReader reader = new PdfReader(input); PdfStamper stamper = new PdfStamper(reader, output); try { PdfReaderContentParser parser = new PdfReaderContentParser(reader); for (int pageNr = 1; pageNr <= reader.getNumberOfPages(); pageNr++) { SearchTextLocationExtractionStrategy strategy = new SearchTextLocationExtractionStrategy(pattern); parser.processContent(pageNr, strategy, Collections.emptyMap()).getResultantText(); Collection<TextRectangle> locations = strategy.getLocations(null); if (locations.isEmpty()) continue; PdfContentByte canvas = stamper.getOverContent(pageNr); canvas.setRGBColorStroke(255, 255, 0); for (TextRectangle location : locations) { canvas.rectangle(location.getMinX(), location.getMinY(), location.getWidth(), location.getHeight()); } canvas.stroke(); } stamper.close(); } finally { reader.close(); } }
Example 13
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 14
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 without rotation. Everything looks ok. * </p> * @see #testCreateEllipse() * @see #testCreateEllipseOnRotated() * @see #testCreateEllipseAppearanceOnRotated() * @see #testCreateCorrectEllipseAppearanceOnRotated() */ @Test public void testCreateEllipseAppearance() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-ellipse-appearance.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); 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 15
Source File: ExtractSuperAndSubInLine.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
void markLineBoundaries(String resource, int startPage, int endPage) throws IOException, DocumentException { String name = new File(resource).getName(); String target = String.format("%s-lines-%s-%s.pdf", name, startPage, endPage); InputStream resourceStream = getClass().getResourceAsStream(resource); try { PdfReader reader = new PdfReader(resourceStream); PdfReaderContentParser parser = new PdfReaderContentParser(reader); System.out.printf("\nLine boundaries in %s\n", name); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, target))); for (int page = startPage; page < endPage; page++) { System.out.printf("\n Page %s\n ", page); TextLineFinder finder = new TextLineFinder(); parser.processContent(page, finder); PdfContentByte over = stamper.getOverContent(page); Rectangle mediaBox = reader.getPageSize(page); for (float flip: finder.verticalFlips) { System.out.printf(" %s", flip); over.moveTo(mediaBox.getLeft(), flip); over.lineTo(mediaBox.getRight(), flip); } System.out.println(); over.stroke(); } stamper.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
Example 16
Source File: AddField.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/35630320/itext-java-android-adding-fields-to-existing-pdf"> * iText - Java Android - Adding fields to existing pdf * </a> * <p> * There actually are two issues in the OP's code: * </p> * <ol> * <li>he creates the fields with empty names * <li>he doesn't set border colors for his fields * </ol> * <p> * These issues are fixed in {@link #testAddLikePasquierCorentin()}, * {@link CheckboxCellEvent}, and {@link MyCellField} below. * </p> */ @Test public void testAddLikePasquierCorentin() throws IOException, DocumentException { File myFile = new File(RESULT_FOLDER, "preface-withField.pdf"); try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/preface.pdf"); OutputStream output = new FileOutputStream(myFile) ) { PdfReader pdfReader = new PdfReader(resource); pdfStamper = new PdfStamper(pdfReader, output); PdfContentByte canvas1; PdfContentByte canvas2; canvas1 = pdfStamper.getOverContent(1); canvas2 = pdfStamper.getOverContent(2); PdfPCell cellFillFieldPage1 = new PdfPCell(); // change: Use a non-empty name cellFillFieldPage1.setCellEvent(new MyCellField("A", 1)); cellFillFieldPage1.setFixedHeight(15); cellFillFieldPage1.setBorder(Rectangle.NO_BORDER); cellFillFieldPage1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellCheckBoxPage2 = new PdfPCell(); // change: Use a non-empty name different from the one above cellCheckBoxPage2.setCellEvent(new CheckboxCellEvent("B", false, 2)); cellCheckBoxPage2.setBorder(Rectangle.NO_BORDER); // ************** PAGE 1 ************** // // SET TABLE PdfPTable tableSection1Page1 = new PdfPTable(1); tableSection1Page1.setTotalWidth(136); tableSection1Page1.setWidthPercentage(100.0f); tableSection1Page1.setLockedWidth(true); // ADD CELLS TO TABLE tableSection1Page1.addCell(cellFillFieldPage1); // PRINT TABLES tableSection1Page1.writeSelectedRows(0, -1, 165, 530, canvas1); // ************ PAGE 2 ************ // // SET TABLES PdfPTable tableSection1Page2 = new PdfPTable(1); tableSection1Page2.setTotalWidth(10); tableSection1Page2.setWidthPercentage(100.0f); tableSection1Page2.setLockedWidth(true); // ADD CELLS TO TABLE tableSection1Page2.addCell(cellCheckBoxPage2); // PRINT TABLES tableSection1Page2.writeSelectedRows(0, -1, 182, 536, canvas2); // I tried this, but it didn't change anything pdfStamper.setFormFlattening(false); pdfStamper.close(); pdfReader.close(); } }
Example 17
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(); }