com.itextpdf.text.Image Java Examples
The following examples show how to use
com.itextpdf.text.Image.
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: PDFMigrationReportWriter.java From bonita-studio with GNU General Public License v2.0 | 7 votes |
private void createLegend(Paragraph mainPara) throws BadElementException, MalformedURLException, IOException { mainPara.add(new Chunk(" ",legendFont)); Image im = getImageForStatus(IStatus.OK); mainPara.add(new Chunk(im, 0, 0, false)); mainPara.add(new Chunk(" ",legendFont)); mainPara.add(new Chunk(Messages.noActionRequired,legendFont)); mainPara.add(new Chunk(" ",legendFont)); im = getImageForStatus(IStatus.WARNING); mainPara.add(new Chunk(im, 0, 0, false)); mainPara.add(new Chunk(" ",legendFont)); mainPara.add(new Chunk(Messages.reviewRequired,legendFont)); mainPara.add(new Chunk(" ",legendFont)); im = getImageForStatus(IStatus.ERROR); mainPara.add(new Chunk(im, 0, 0, false)); mainPara.add(new Chunk(" ",legendFont)); mainPara.add(new Chunk(Messages.actionRequired,legendFont)); }
Example #2
Source File: PDFSampleMain.java From tutorials with MIT License | 7 votes |
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException { Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI()); Image img = Image.getInstance(path.toAbsolutePath().toString()); img.scalePercent(10); PdfPCell imageCell = new PdfPCell(img); table.addCell(imageCell); PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2")); horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(horizontalAlignCell); PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3")); verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell(verticalAlignCell); }
Example #3
Source File: StampInLayer.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
public static byte[] stampLayer(InputStream _pdfFile, Image iImage, int x, int y, String layername, boolean readLayers) throws IOException, DocumentException { PdfReader reader = new PdfReader(_pdfFile); try ( ByteArrayOutputStream ms = new ByteArrayOutputStream() ) { PdfStamper stamper = new PdfStamper(reader, ms); //Don't delete otherwise the stamper flattens the layers if (readLayers) stamper.getPdfLayers(); PdfLayer logoLayer = new PdfLayer(layername, stamper.getWriter()); PdfContentByte cb = stamper.getUnderContent(1); cb.beginLayer(logoLayer); //300dpi iImage.scalePercent(24f); iImage.setAbsolutePosition(x, y); cb.addImage(iImage); cb.endLayer(); stamper.close(); return (ms.toByteArray()); } }
Example #4
Source File: PersonalReportPdfCommand.java From bamboobsc with Apache License 2.0 | 6 votes |
private void putSignature(PdfPTable table, Context context) throws Exception { String uploadOid = (String)context.get("uploadSignatureOid"); if ( StringUtils.isBlank(uploadOid) ) { return; } byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid ); if ( null == imageBytes ) { return; } Image signatureImgObj = Image.getInstance( imageBytes ); signatureImgObj.setWidthPercentage(40f); PdfPCell cell = new PdfPCell(); cell.setBorder( Rectangle.NO_BORDER ); cell.addElement(signatureImgObj); table.addCell(cell); }
Example #5
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createMultiUseImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); BufferedImage bim = new BufferedImage(500, 250, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 250, 250); g2d.dispose(); Image image = Image.getInstance(bim, null); document.add(image); document.add(image); document.add(image); document.close(); return baos.toByteArray(); }
Example #6
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createRotatedImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte directContent = writer.getDirectContent(); BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 500, 500); g2d.dispose(); Image image = Image.getInstance(bim, null); directContent.addImage(image, 0, 500, -500, 0, 550, 50); document.close(); return baos.toByteArray(); }
Example #7
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createSimpleImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 500, 500); g2d.dispose(); Image image = Image.getInstance(bim, null); document.add(image); document.close(); return baos.toByteArray(); }
Example #8
Source File: KpiReportPdfCommand.java From bamboobsc with Apache License 2.0 | 6 votes |
private void putSignature(PdfPTable table, Context context) throws Exception { String uploadOid = (String)context.get("uploadSignatureOid"); if ( StringUtils.isBlank(uploadOid) ) { return; } byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid ); if ( null == imageBytes ) { return; } Image signatureImgObj = Image.getInstance( imageBytes ); signatureImgObj.setWidthPercentage(40f); PdfPCell cell = new PdfPCell(); cell.setBorder( Rectangle.NO_BORDER ); cell.addElement(signatureImgObj); table.addCell(cell); }
Example #9
Source File: OrganizationReportPdfCommand.java From bamboobsc with Apache License 2.0 | 6 votes |
private void putSignature(PdfPTable table, Context context) throws Exception { String uploadOid = (String)context.get("uploadSignatureOid"); if ( StringUtils.isBlank(uploadOid) ) { return; } byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid ); if ( null == imageBytes ) { return; } Image signatureImgObj = Image.getInstance( imageBytes ); signatureImgObj.setWidthPercentage(40f); PdfPCell cell = new PdfPCell(); cell.setBorder( Rectangle.NO_BORDER ); cell.addElement(signatureImgObj); table.addCell(cell); }
Example #10
Source File: PDFExport.java From MtgDesktopCompanion with GNU General Public License v3.0 | 6 votes |
private PdfPCell getCells(MagicCard card) throws BadElementException, IOException { Image image1 = null; try { image1 = Image.getInstance(MTGControler.getInstance().getEnabled(MTGPictureProvider.class).getPicture(card, null), null); } catch (Exception e) { image1 = Image.getInstance(MTGControler.getInstance().getEnabled(MTGPictureProvider.class).getBackPicture(), null); } int h = getInt("CARD_HEIGHT"); int w = getInt("CARD_WIDTH"); image1.scaleAbsolute(w, h); PdfPCell cell = new PdfPCell(image1, false); cell.setBorder(0); cell.setPadding(5); return cell; }
Example #11
Source File: AddRotatedImage.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
void addRotatedImage(PdfContentByte contentByte, Image image, float x, float y, float width, float height, float rotation) throws DocumentException { // Draw image at x,y without rotation contentByte.addImage(image, width, 0, 0, height, x, y); // Draw image as if the previous image was rotated around its center // Image starts out being 1x1 with origin in lower left // Move origin to center of image AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5); // Stretch it to its dimensions AffineTransform B = AffineTransform.getScaleInstance(width, height); // Rotate it AffineTransform C = AffineTransform.getRotateInstance(rotation); // Move it to have the same center as above AffineTransform D = AffineTransform.getTranslateInstance(x + width/2, y + height/2); // Concatenate AffineTransform M = (AffineTransform) A.clone(); M.preConcatenate(B); M.preConcatenate(C); M.preConcatenate(D); //Draw contentByte.addImage(image, M); }
Example #12
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 #13
Source File: PdfCleanUpContentOperator.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
private void updateImageStream(PRStream imageStream, byte[] newData) throws BadElementException, IOException, BadPdfFormatException { PdfImage image = new PdfImage(Image.getInstance(newData), "", null); if (imageStream.contains(PdfName.SMASK)) { image.put(PdfName.SMASK, imageStream.get(PdfName.SMASK)); } if (imageStream.contains(PdfName.MASK)) { image.put(PdfName.MASK, imageStream.get(PdfName.MASK)); } if (imageStream.contains(PdfName.SMASKINDATA)) { image.put(PdfName.SMASKINDATA, imageStream.get(PdfName.SMASKINDATA)); } imageStream.clear(); imageStream.putAll(image); imageStream.setDataRaw(image.getBytes()); }
Example #14
Source File: PDF2ImageExample.java From tutorials with MIT License | 5 votes |
private static void generatePDFFromImage(String filename, String extension) throws IOException, BadElementException, DocumentException { Document document = new Document(); String input = filename + "." + extension; String output = "src/output/" + extension + ".pdf"; FileOutputStream fos = new FileOutputStream(output); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); document.add(Image.getInstance((new URL(input)))); document.close(); writer.close(); }
Example #15
Source File: PDFMigrationReportWriter.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
private com.itextpdf.text.Image getImageForStatus(int status) throws BadElementException, MalformedURLException, IOException { switch (status) { case IStatus.OK: Image im = Image.getInstance(FileLocator.toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/valid.png")));im.setCompressionLevel(12);im.scaleToFit(12, 12);return im; case IStatus.WARNING: im = Image.getInstance(FileLocator.toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/warning.gif")));im.setCompressionLevel(12);im.scaleToFit(16, 16);return im; case IStatus.ERROR: im = Image.getInstance(FileLocator.toFileURL(MigrationPlugin.getDefault().getBundle().getResource("/icons/error.png")));im.setCompressionLevel(12);im.scaleToFit(12, 12);return im; default:break; } return null; }
Example #16
Source File: AbstractSignatureActionExecuter.java From CounterSign with GNU Affero General Public License v3.0 | 5 votes |
/** * Gets the X value for centering the signature stamp * * @param r * @param img * @return */ protected float getCenterX(Rectangle r, Image img) { float x = 0; float pdfwidth = r.getWidth(); float imgwidth = img.getWidth(); x = (pdfwidth - imgwidth) / 2; return x; }
Example #17
Source File: AbstractSignatureActionExecuter.java From CounterSign with GNU Affero General Public License v3.0 | 5 votes |
/** * Gets the Y value for centering the signature stamp * * @param r * @param img * @return */ protected float getCenterY(Rectangle r, Image img) { float y = 0; float pdfheight = r.getHeight(); float imgheight = img.getHeight(); y = (pdfheight - imgheight) / 2; return y; }
Example #18
Source File: PdfReportPageNumber.java From bdf3 with Apache License 2.0 | 5 votes |
/** * Adds a header to every page * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { PdfPTable table = new PdfPTable(3); try { table.setWidths(new int[]{40,5,10}); table.setTotalWidth(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); Font font=new Font(chineseFont,8); font.setColor(new BaseColor(55,55,55)); Paragraph paragraph=new Paragraph("第 "+writer.getPageNumber()+" 页 共",font); paragraph.setAlignment(Element.ALIGN_RIGHT); table.addCell(paragraph); Image img=Image.getInstance(total); img.scaleAbsolute(28, 28); PdfPCell cell = new PdfPCell(img); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); PdfPCell c = new PdfPCell(new Paragraph("页",font)); c.setHorizontalAlignment(Element.ALIGN_LEFT); c.setBorder(Rectangle.NO_BORDER); table.addCell(c); float center=(document.getPageSize().getWidth())/2-120/2; table.writeSelectedRows(0, -1,center,30, writer.getDirectContent()); } catch(DocumentException de) { throw new ExceptionConverter(de); } }
Example #19
Source File: StampInLayer.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/31507132/itextsharp-form-gets-flattened-even-when-the-formflattening-property-is-false"> * Itextsharp form gets flattened even when the FormFlattening property is false * </a> * <p> * Reproducing the issue without work-around. * </p> */ @Test public void testStampInLayerOnLayeredBug() throws IOException, DocumentException { try ( InputStream source = getClass().getResourceAsStream("House_Plan_Final.pdf"); InputStream image = getClass().getResourceAsStream("Willi-1.jpg")) { Image iImage = Image.getInstance(StreamUtil.inputStreamToArray(image)); byte[] result = stampLayer(source, iImage, 100, 100, "Logos", false); Files.write(new File(RESULT_FOLDER, "House_Plan_Final-stamped-bug.pdf").toPath(), result); } }
Example #20
Source File: StampInLayer.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/31507132/itextsharp-form-gets-flattened-even-when-the-formflattening-property-is-false"> * Itextsharp form gets flattened even when the FormFlattening property is false * </a> * <p> * Reproducing the issue with work-around. * </p> */ @Test public void testStampInLayerOnLayeredWorkAround() throws IOException, DocumentException { try ( InputStream source = getClass().getResourceAsStream("House_Plan_Final.pdf"); InputStream image = getClass().getResourceAsStream("Willi-1.jpg")) { Image iImage = Image.getInstance(StreamUtil.inputStreamToArray(image)); byte[] result = stampLayer(source, iImage, 100, 100, "Logos", true); Files.write(new File(RESULT_FOLDER, "House_Plan_Final-stamped-workAround.pdf").toPath(), result); } }
Example #21
Source File: PdfGenerator.java From book118-downloader with MIT License | 5 votes |
/** * 使用图片创建PDF文件 * * @param srcPahOfImg 图片文件夹路径 * @param desPathOfPdf PDF存储路径 * @throws DocumentException pdf相关错误 * @throws IOException 图片相关错误 */ public static void creatPDF(String srcPahOfImg, String desPathOfPdf, String sSufix) throws DocumentException, IOException { File file = new File(srcPahOfImg); File[] picFiles = file.listFiles(); if (picFiles == null || picFiles.length == 0) { return; } List<File> files = Arrays.asList(picFiles); files.sort((o1, o2) -> o1.getName().compareTo(o2.getName())); //需要根据第一页创建document的大小 //如果不根据第一页创建,即使修改document的大小也不会生效,困惑 // Fix: 创建文档是需要指定文档的尺寸, 该尺寸为文档的默认尺寸 // Fix: setPageSize 修改的是加入文档的最后一页, 因此需要先添加页,再修改文档大小 Image firstImg = Image.getInstance(files.get(0).getCanonicalPath()); Document document = new Document(new Rectangle(firstImg.getWidth(), firstImg.getHeight()), 0, 0, 0, 0); PdfWriter.getInstance(document, new FileOutputStream(desPathOfPdf)); document.open(); for (File picFile : picFiles) { String sFileName = picFile.getCanonicalPath(); // 过滤出指定后缀名的文件 if (!sFileName.substring(sFileName.lastIndexOf('.') + 1).equals(sSufix)) { continue; } Image img = Image.getInstance(sFileName); document.add(img); document.setPageSize(new Rectangle(img.getWidth(), img.getHeight())); } document.close(); }
Example #22
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
static byte[] createSmaskImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 500, 500); g2d.dispose(); BufferedImage bmask = new BufferedImage(500, 500, BufferedImage.TYPE_BYTE_GRAY); g2d = bmask.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, 500, 500); g2d.setColor(Color.BLACK); g2d.fillRect(200, 0, 100, 500); g2d.dispose(); Image image = Image.getInstance(bim, null); Image mask = Image.getInstance(bmask, null, true); mask.makeMask(); image.setImageMask(mask); document.add(image); document.close(); return baos.toByteArray(); }
Example #23
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
static byte[] createClippingTextPdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte directContent = writer.getDirectContent(); directContent.beginText(); directContent.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_CLIP); directContent.setTextMatrix(AffineTransform.getTranslateInstance(100, 400)); directContent.setFontAndSize(BaseFont.createFont(), 100); directContent.showText("Test"); directContent.endText(); BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 500, 500); g2d.dispose(); Image image = Image.getInstance(bim, null); directContent.addImage(image, 500, 0, 0, 599, 50, 50); document.close(); return baos.toByteArray(); }
Example #24
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 #25
Source File: BinaryTransparency.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/39119776/itext-binary-transparency-bug"> * iText binary transparency bug * </a> * <p> * Indeed, there is a bug in {@link Image#getInstance(Image, Color, boolean)}, * the loop which determines whether to use a transparency array or a softmask * is erroneous and here falsely indicates a transparency array suffices. * </p> */ @Test public void testBinaryTransparencyBug() throws IOException, DocumentException { Document document = new Document(); File file = new File(RESULT_FOLDER, "binary_transparency_bug.pdf"); FileOutputStream outputStream = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); addBackground(writer); document.add(new Paragraph("Binary transparency bug test case")); document.add(new Paragraph("OK: Visible image (opaque pixels are red, non opaque pixels are black)")); document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.red,false,null), null)); document.newPage(); addBackground(writer); document.add(new Paragraph("Suspected bug: invisible image (both opaque an non opaque pixels have the same color)")); document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.black,false,null), null)); document.newPage(); addBackground(writer); document.add(new Paragraph("Analysis: Aliasing makes the problem disappear, because this way the image is not binary transparent any more")); document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.black,true,null), null)); document.newPage(); addBackground(writer); document.add(new Paragraph("Analysis: Setting the color of the transparent pixels to anything but black makes the problem go away, too")); document.add(com.itextpdf.text.Image.getInstance(createBinaryTransparentAWTImage(Color.black,false,Color.red), null)); document.close(); }
Example #26
Source File: BinaryTransparency.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
@BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); bkgnd = Image.getInstance(new URL("http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/images/berlin2013.jpg")); bkgnd.scaleAbsolute(PageSize.A4); bkgnd.setAbsolutePosition(0, 0); }
Example #27
Source File: JFreeChartTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName) { PdfWriter writer = null; Document document = new Document(); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte pdfContentByte = writer.getDirectContent(); PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(50, 50); Graphics2D graphics2d = new PdfGraphics2D(pdfTemplateChartHolder, 50, 50); Rectangle2D chartRegion = new Rectangle2D.Double(0, 0, 50, 50); chart.draw(graphics2d, chartRegion); graphics2d.dispose(); Image chartImage = Image.getInstance(pdfTemplateChartHolder); document.add(chartImage); PdfPTable table = new PdfPTable(5); // the cell object // we add a cell with colspan 3 PdfPCell cellX = new PdfPCell(new Phrase("A")); cellX.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); cellX.setRowspan(6); table.addCell(cellX); PdfPCell cellA = new PdfPCell(new Phrase("A")); cellA.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); cellA.setColspan(4); table.addCell(cellA); PdfPCell cellB = new PdfPCell(new Phrase("B")); table.addCell(cellB); PdfPCell cellC = new PdfPCell(new Phrase("C")); table.addCell(cellC); PdfPCell cellD = new PdfPCell(new Phrase("D")); table.addCell(cellD); PdfPCell cellE = new PdfPCell(new Phrase("E")); table.addCell(cellE); PdfPCell cellF = new PdfPCell(new Phrase("F")); table.addCell(cellF); PdfPCell cellG = new PdfPCell(new Phrase("G")); table.addCell(cellG); PdfPCell cellH = new PdfPCell(new Phrase("H")); table.addCell(cellH); PdfPCell cellI = new PdfPCell(new Phrase("I")); table.addCell(cellI); PdfPCell cellJ = new PdfPCell(new Phrase("J")); cellJ.setColspan(2); cellJ.setRowspan(3); //instead of // cellJ.setImage(chartImage); //the OP now uses Chunk chunk = new Chunk(chartImage, 20, -50); cellJ.addElement(chunk); //presumably with different contents of the other cells at hand table.addCell(cellJ); PdfPCell cellK = new PdfPCell(new Phrase("K")); cellK.setColspan(2); table.addCell(cellK); PdfPCell cellL = new PdfPCell(new Phrase("L")); cellL.setColspan(2); table.addCell(cellL); PdfPCell cellM = new PdfPCell(new Phrase("M")); cellM.setColspan(2); table.addCell(cellM); document.add(table); } catch (Exception e) { e.printStackTrace(); } document.close(); }
Example #28
Source File: TableWithSpan.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
PdfPCell getPiccell(int w, int h) { try { Image image = Image.getInstance("src/test/resources/mkl/testarea/itext5/content/2x2colored.png"); image.scaleAbsolute(w, h); return new PdfPCell(image); } catch (BadElementException | IOException e) { throw new RuntimeException(e); } }
Example #29
Source File: PdfCleanUpRenderListener.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
public void renderImage(ImageRenderInfo renderInfo) { List<Rectangle> areasToBeCleaned = getImageAreasToBeCleaned(renderInfo); if (areasToBeCleaned == null) { chunks.add(new PdfCleanUpContentChunk.Image(false, null)); } else { try { PdfImageObject pdfImage = renderInfo.getImage(); byte[] imageBytes = processImage(pdfImage.getImageAsBytes(), areasToBeCleaned); if (renderInfo.getRef() == null && pdfImage != null) { // true => inline image PdfDictionary dict = pdfImage.getDictionary(); PdfObject imageMask = dict.get(PdfName.IMAGEMASK); Image image = Image.getInstance(imageBytes); if (imageMask == null) { imageMask = dict.get(PdfName.IM); } if (imageMask != null && imageMask.equals(PdfBoolean.PDFTRUE)) { image.makeMask(); } PdfContentByte canvas = getContext().getCanvas(); canvas.addImage(image, 1, 0, 0, 1, 0, 0, true); } else if (pdfImage != null && imageBytes != pdfImage.getImageAsBytes()) { chunks.add(new PdfCleanUpContentChunk.Image(true, imageBytes)); } } catch (Exception e) { throw new RuntimeException(e); } } }
Example #30
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(); }