private PdfPCell buildPdfPCell(HeaderFooter phf,String text,int type){ PdfPCell cell=new PdfPCell(); cell.setPadding(0); cell.setBorder(Rectangle.NO_BORDER); Font font=FontBuilder.getFont(phf.getFontFamily(), phf.getFontSize(), phf.isBold(), phf.isItalic(),phf.isUnderline()); String fontColor=phf.getForecolor(); if(StringUtils.isNotEmpty(fontColor)){ String[] color=fontColor.split(","); font.setColor(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2])); } Paragraph graph=new Paragraph(text,font); cell.setPhrase(graph); switch(type){ case 1: cell.setHorizontalAlignment(Element.ALIGN_LEFT); break; case 2: cell.setHorizontalAlignment(Element.ALIGN_CENTER); break; case 3: cell.setHorizontalAlignment(Element.ALIGN_RIGHT); break; } cell.setVerticalAlignment(Element.ALIGN_MIDDLE); return cell; }
/** * <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(); } }
@Test public void sign50MBrunoAppend() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/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, "50m-signedBrunoAppend.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(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); }
public Document createDocument(File pdfFile) throws DocumentException, IOException{ Document document = new Document(new Rectangle(pageWidth, pageHeight)); document.setPageSize(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile)); //写入页尾 this.setFooter(writer); writer.setFullCompression(); writer.setPdfVersion(PdfWriter.VERSION_1_4); document.open(); // //加入二维码图片 // Image image = Image.getInstance(System.getProperty(appConfig.getValue("app.root"))+"/images/logoqrcode.png"); // image.scaleAbsolute(40,40);//控制图片大小 // image.setAlignment(Image.LEFT); // document.add(image); return document; }
public void print(String plot_pdf) { try { float width = jframe.getSize().width, height = jframe.getSize().height; Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(plot_pdf)); document.open(); PdfContentByte canvas = writer.getDirectContent(); PdfTemplate template = canvas.createTemplate(width, height); Graphics2D g2d = new PdfGraphics2D(template, width, height); jframe.paint(g2d); g2d.dispose(); canvas.addTemplate(template, 0, 0); document.close(); } catch (FileNotFoundException | DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
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); }
/** * Increase the page number. * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ @Override public void onStartPage(PdfWriter writer, Document document) { pagenumber++; System.out.println("ON Start Page PDF"); Rectangle rect = writer.getBoxSize("art"); /* header ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_RIGHT, header[0], rect.getRight(), rect.getTop(), 0); */ Font font = new Font(); font.setSize(8); if (G.licensePDF) { ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_CENTER, new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA")),font), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0); ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_CENTER, new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA2")),font), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 9, 0); } }
void split(PdfReader reader, int page) throws IOException { PdfImportedPage importedPage = writer.getImportedPage(reader, page); Rectangle pageSizeToImport = reader.getPageSize(page); Iterable<Rectangle> rectangles = determineSplitRectangles(reader, page); for (Rectangle rectangle : rectangles) { newPage(rectangle); PdfContentByte directContent = writer.getDirectContent(); directContent.saveState(); directContent.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight()); directContent.clip(); directContent.newPath(); writer.getDirectContent().addTemplate(importedPage, -pageSizeToImport.getLeft(), -pageSizeToImport.getBottom()); directContent.restoreState(); } }
@Override public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS]; float xTransition = position.getLeft() + (position.getRight() - position.getLeft()) * (percent/100.0f); float yTransition = (position.getTop() + position.getBottom()) / 2f; float radius = (position.getRight() - position.getLeft()) * 0.025f; PdfShading axial = PdfShading.simpleAxial(canvas.getPdfWriter(), xTransition - radius, yTransition, xTransition + radius, yTransition, leftColor, rightColor); PdfShadingPattern shading = new PdfShadingPattern(axial); canvas.saveState(); canvas.setShadingFill(shading); canvas.rectangle(position.getLeft(), position.getBottom(), position.getWidth(), position.getHeight()); // canvas.clip(); canvas.fill(); canvas.restoreState(); }
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())); }
private byte[] processImage(byte[] imageBytes, List<Rectangle> areasToBeCleaned) { if (areasToBeCleaned.isEmpty()) { return imageBytes; } try { BufferedImage image = Imaging.getBufferedImage(imageBytes); ImageInfo imageInfo = Imaging.getImageInfo(imageBytes); cleanImage(image, areasToBeCleaned); // Apache can only read JPEG, so we should use awt for writing in this format if (imageInfo.getFormat() == ImageFormats.JPEG) { return getJPGBytes(image); } else { Map<String, Object> params = new HashMap<String, Object>(); if (imageInfo.getFormat() == ImageFormats.TIFF) { params.put(ImagingConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_LZW); } return Imaging.writeImageToBytes(image, imageInfo.getFormat(), params); } } catch (Exception e) { throw new RuntimeException(e); } }
private void cleanImage(BufferedImage image, List<Rectangle> areasToBeCleaned) { Graphics2D graphics = image.createGraphics(); graphics.setColor(CLEANED_AREA_FILL_COLOR); // A rectangle in the areasToBeCleaned list is treated to be in standard [0, 1]x[0,1] image space // (y varies from bottom to top and x from left to right), so we should scale the rectangle and also // invert and shear the y axe for (Rectangle rect : areasToBeCleaned) { int scaledBottomY = (int) Math.ceil(rect.getBottom() * image.getHeight()); int scaledTopY = (int) Math.floor(rect.getTop() * image.getHeight()); int x = (int) Math.ceil(rect.getLeft() * image.getWidth()); int y = scaledTopY * -1 + image.getHeight(); int width = (int) Math.floor(rect.getRight() * image.getWidth()) - x; int height = scaledTopY - scaledBottomY; graphics.fillRect(x, y, width, height); } graphics.dispose(); }
/** * Calculates intersection of the image and the render filter region in the coordinate system relative to the image. * * @return <code>null</code> if the image is not allowed, {@link java.util.List} of * {@link com.itextpdf.text.Rectangle} objects otherwise. */ protected List<Rectangle> getCoveredAreas(ImageRenderInfo renderInfo) { Rectangle imageRect = calcImageRect(renderInfo); List<Rectangle> coveredAreas = new ArrayList<Rectangle>(); if (imageRect == null) { return null; } for (Rectangle rectangle : rectangles) { Rectangle intersectionRect = intersection(imageRect, rectangle); if (intersectionRect != null) { // True if the image is completely covered if (imageRect.equals(intersectionRect)) { return null; } coveredAreas.add(transformIntersection(renderInfo.getImageCTM(), intersectionRect)); } } return coveredAreas; }
/** * Note: this method will close all unclosed subpaths of the passed path. * * @param fillingRule If the subpath is contour, pass any value. */ protected Path filterFillPath(Path path, Matrix ctm, int fillingRule) { path.closeAllSubpaths(); Clipper clipper = new DefaultClipper(); addPath(clipper, path); for (Rectangle rectangle : rectangles) { Point2D[] transfRectVertices = transformPoints(ctm, true, getVertices(rectangle)); addRect(clipper, transfRectVertices, PolyType.CLIP); } PolyFillType fillType = PolyFillType.NON_ZERO; if (fillingRule == PathPaintingRenderInfo.EVEN_ODD_RULE) { fillType = PolyFillType.EVEN_ODD; } PolyTree resultTree = new PolyTree(); clipper.execute(ClipType.DIFFERENCE, resultTree, fillType, PolyFillType.NON_ZERO); return convertToPath(resultTree); }
private PdfPTable createDateTable(PdfContentByte cb, Receipt receipt) throws DocumentException { PdfPTable tableForDate = new PdfPTable(1); float[] rowForDate = { 110f }; tableForDate.setTotalWidth(rowForDate); tableForDate.getDefaultCell() .setBorder(Rectangle.NO_BORDER); tableForDate.addCell(new Phrase(new Chunk("Datum der Zuwendung:", textFont))); tableForDate.addCell(new Phrase(new Chunk(" ", textFont))); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN); for (final Cart cart : receipt.getCarts()) { cal.setTimeInMillis(cart.getTimeStamp()); final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR); PdfPCell cell = new PdfPCell(new Phrase(new Chunk(date, textFontUserData))); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setBorder(PdfPCell.NO_BORDER); tableForDate.addCell(cell); } return tableForDate; }
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { PdfWriter writer = canvases[0].getPdfWriter(); float x = position.getLeft(); float y = position.getBottom(); Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5); RadioCheckField checkbox = new RadioCheckField( writer, rect, name, "Yes"); checkbox.setCheckType(RadioCheckField.TYPE_CROSS); checkbox.setChecked(check); // change: set border color checkbox.setBorderColor(BaseColor.BLACK); try { pdfStamper.addAnnotation(checkbox.getCheckField(), page); } catch (Exception e) { throw new ExceptionConverter(e); } }
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException { PdfContentByte cb = writer.getDirectContent(); PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight()); cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight()); cs.fill(); cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12); cs.beginText(); cs.setLeading(12 + 1.75f); cs.moveText(.75f, rect.getHeight() - 12 + .75f); cs.showText(contents); cs.endText(); return PdfAnnotation.createFreeText(writer, rect, contents, cs); }
private void createReceiptHeaderAndTextBelow(PdfContentByte cb) throws DocumentException { PdfPTable headerTable = new PdfPTable(1); float[] rows = { 450f }; headerTable.setTotalWidth(rows); headerTable.getDefaultCell() .setBorder(Rectangle.NO_BORDER); headerTable.addCell(new Phrase(new Chunk("Bestätigung über Geldzuwendungen", textFontForReceiptHeader))); headerTable.writeSelectedRows(0, 1, 75f, 625, cb); PdfPTable table = new PdfPTable(1); table.setTotalWidth(rows); table.getDefaultCell() .setBorder(Rectangle.NO_BORDER); table.getDefaultCell() .setLeading(8f, 0); table.addCell(new Phrase(new Chunk("im Sinne des §10b des Einkommensteuergesetzes", textFont))); table.addCell(new Phrase(new Chunk("an eine der in §5 Abs. 1 Nr. 9 des Körperschaftsteuergesetzes bezeichneten", textFont))); table.addCell(new Phrase(new Chunk("Körperschaften, Personenvereinigungen oder Vermögensmassen", textFont))); table.writeSelectedRows(0, 3, 75f, 590, cb); }
/** * <a href="https://stackoverflow.com/questions/46466747/how-to-split-a-pdf-page-in-java"> * How to split a PDF page in java? * </a> * <p> * This test shows how to split the pages of a document into tiles of A6 * size using the {@link Abstract2DPdfPageSplittingTool}. * </p> */ @Test public void testSplitDocumentA6() throws IOException, DocumentException { try (InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-A6.pdf"))) { Abstract2DPdfPageSplittingTool tool = new Abstract2DPdfPageSplittingTool() { @Override protected Iterable<Rectangle> determineSplitRectangles(PdfReader reader, int page) { Rectangle targetSize = PageSize.A6; List<Rectangle> rectangles = new ArrayList<>(); Rectangle pageSize = reader.getPageSize(page); for (float y = pageSize.getTop(); y > pageSize.getBottom() + 5; y-=targetSize.getHeight()) { for (float x = pageSize.getLeft(); x < pageSize.getRight() - 5; x+=targetSize.getWidth()) { rectangles.add(new Rectangle(x, y - targetSize.getHeight(), x + targetSize.getWidth(), y)); } } return rectangles; } }; tool.split(result, new PdfReader(resource)); } }
/** * <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(); } }
/** * <a href="http://stackoverflow.com/questions/35374110/how-do-i-use-itext-to-have-a-landscaped-pdf-on-half-of-a-a4-back-to-portrait-and"> * How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4 * </a> * <p> * This sample shows how to rotate and enlarge the upper half of an A4 page to fit into a new A4 page. * </p> */ @Test public void testRotateAndZoomUpperHalfPage() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test-upperHalf.pdf")) ) { PdfReader reader = new PdfReader(resource); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, result); document.open(); double sqrt2 = Math.sqrt(2); Rectangle pageSize = reader.getPageSize(1); PdfImportedPage importedPage = writer.getImportedPage(reader, 1); writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2); document.close(); } }
static byte[] createSimpleCircleGraphicsPdf(int radius, int gap, int count) throws DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); float y = writer.getPageSize().getTop(); for (int i = 0; i < count; i++) { Rectangle pageSize = writer.getPageSize(); if (y <= pageSize.getBottom() + 2*radius) { y = pageSize.getTop(); writer.getDirectContent().fillStroke(); document.newPage(); } writer.getDirectContent().circle(pageSize.getLeft() + pageSize.getWidth() * Math.random(), y-radius, radius); y-= 2*radius + gap; } writer.getDirectContent().fillStroke(); document.close(); return baos.toByteArray(); }
private PdfPTable createPriceTable(PdfContentByte cb, Receipt receipt) throws DocumentException { PdfPTable tableForPrices = new PdfPTable(1); float[] rowForTotalPrice = { 250f }; tableForPrices.setTotalWidth(rowForTotalPrice); tableForPrices.getDefaultCell() .setBorder(Rectangle.NO_BORDER); tableForPrices.addCell(new Phrase(new Chunk("Betrag der Zuwendung in Ziffern:", textFont))); tableForPrices.addCell(new Phrase(new Chunk(" ", textFont))); Double totalPrice = 0.0; for (final Cart cart : receipt.getCarts()) { tableForPrices.addCell(new Phrase(new Chunk(cart.getTotalPrice() .toString() + " €", textFontUserData))); totalPrice += cart.getTotalPrice() .doubleValue(); } String formattedPrice = priceFormat.format(totalPrice) .toString(); tableForPrices.addCell(new Phrase(new Chunk("Gesamt: " + formattedPrice + " €", textFontUserData))); return tableForPrices; }
@Test public void sign50MBrunoPartialAppend() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.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, "50m-signedBrunoPartialAppend.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(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); }
@Test public void sign2g() 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-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(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); }
public static void createCircleAndText(PdfContentByte cb, String text, float xCoord, float yCoord, float radius, Font textFont, int circleColorRed, int circleColorGreen, int circleColorBlue) throws DocumentException, IOException { cb.saveState(); cb.setRGBColorFill(circleColorRed, circleColorGreen, circleColorBlue); cb.circle(xCoord, yCoord, radius); cb.fill(); cb.stroke(); cb.restoreState(); PdfPTable table = new PdfPTable(1); float[] rows = { 595f }; table.setTotalWidth(rows); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); table.getDefaultCell().setFixedHeight(radius * 2); table.addCell(new Phrase(new Chunk(text, textFont))); table.writeSelectedRows(0, 1, 0, yCoord + radius, cb); }
@Test public void signCertify2gFix() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g-fix.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-fix-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); }
/** * <a href="http://stackoverflow.com/questions/38278816/remove-header-of-a-pdf-using-itext-pdfcleanupprocessor-does-not-work"> * Remove header of a pdf using iText PdfCleanUpProcessor does not work * </a> * <br/> * <a href="https://www.dropbox.com/s/4u8vupjqc4st3ib/love.pdf?dl=0"> * love.pdf * </a> * <p> * Cannot reproduce, I get a <code>org.apache.commons.imaging.ImageReadException: Invalid marker found in entropy data</code>. * </p> */ @Test public void testRedactLikeShiranSEkanayake() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("love.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "love-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); for(int i=1; i<=reader.getNumberOfPages(); i++) { //System.out.println(i); Rectangle mediabox = reader.getPageSize(i); cleanUpLocations.add(new PdfCleanUpLocation(i, new Rectangle(0,800,1000,1000))); } PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
@Override public void renderGraph(JGraph<?> graph, File file) throws PortException { // Get graph bounds. If not available, do nothing (probably empty graph) Rectangle2D bounds = graph.getGraphBounds(); if (bounds == null) { return; } Rectangle bound = new Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()); try (FileOutputStream fos = new FileOutputStream(file)) { Document document = new Document(bound); // Open file, create PDF document PdfWriter writer = PdfWriter.getInstance(document, fos); // Set some metadata document.addCreator(Version.getAbout()); // Open document, get graphics document.open(); PdfContentByte cb = writer.getDirectContent(); boolean onlyShapes = true; //The embedded fonts most likely do not contain all necessary glyphs, so using outlines instead // onlyShapes makes PDF considerably bigger, but no alternative at the moment PdfGraphics2D pdf2d = new PdfGraphics2D(cb, (float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper(), onlyShapes, false, (float) 100.0); // Render toGraphics(graph, pdf2d); // Cleanup pdf2d.dispose(); document.close(); } catch (DocumentException | IOException e) { throw new PortException(e); } }
public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); if (rect != null) { sumSymboltoFooter(writer, rect); pageNumberFooter(writer, rect); } }
private void pageNumberFooter(PdfWriter writer, Rectangle rect) { Chunk c = new Chunk(String.format(LocaleStrings.getString("page"), writer.getPageNumber(), _maximumPageNumber)); c.setFont(new Font(FontFamily.HELVETICA, 10)); Phrase pagephrase = new Phrase(c); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, pagephrase, rect.getRight() - 60, rect.getBottom() - 30, 0); }
@SuppressWarnings("unused") private void headerText(PdfWriter writer, Rectangle rect) { float center = (rect.getLeft() + rect.getRight()) / 2; ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Header Text"), center, rect.getTop(), 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("01.01.1970"), center, rect.getTop() - 16, 0); }
public void createPDF(String outputFile, ArrayList<Question> qlist, boolean showCorrectAnswer, PageCounter pagecounter, int maximumPageNumber, String inputFolder) throws DocumentException, IOException { _inputFolder = inputFolder; Document document = new Document(PageSize.A4, 50, 50, 70, 50); PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); pdfwriter.setBoxSize("art", new Rectangle(36, 54, 559, 788)); pdfwriter.setPageEvent(new HeaderFooter(maximumPageNumber)); if (pagecounter != null) { pdfwriter.setPageEvent(pagecounter); } document.open(); Paragraph p = new Paragraph(); // p.setSpacingBefore(SPACING); p.setSpacingAfter(SPACING); p.setIndentationLeft(INDENTATION); writeQuestions(p, document, showCorrectAnswer, qlist); document.close(); }
/** * 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); } }
/** * * @param request * @return {@link Rectangle} with cutmark if that is used transformed to postscript points */ public Rectangle getSizeAsRectangle(PdfDocument request){ float bothSidesOfCutmark = 0; if( request.getCutmarks() != null ){ bothSidesOfCutmark = CUT_MARK * 2; } return new Rectangle( millimetersToPostscriptPoints(request.getSize()[0] + bothSidesOfCutmark ), millimetersToPostscriptPoints(request.getSize()[1] + bothSidesOfCutmark ) ); }
public PdfPCellEvent createEvent(final Block block ){ return new PdfPCellEvent(){ public void cellLayout(PdfPCell cell, Rectangle rect,PdfContentByte[] canvas) { float radiusInPs = SizeFactory.millimetersToPostscriptPoints( block.getRadius() ); PdfContentByte cb = canvas[PdfPTable.LINECANVAS]; PdfTemplate template = cb.createTemplate( rect.getWidth() , rect.getHeight()); template.roundRectangle(0, 0, rect.getWidth() ,rect.getHeight() , radiusInPs); template.clip(); template.newPath(); if( block.getBaseColor() != null ){ template.setColorFill(block.getBaseColor()); } Border border = block.getBorder(); if( border != null ){ template.setLineWidth( SizeFactory.millimetersToPostscriptPoints( border.getThickness()) ); template.setColorStroke( border.getBaseColor()); } template.roundRectangle(0, 0, rect.getWidth() ,rect.getHeight() ,radiusInPs); if( block.getBaseColor() != null || border != null ){ if( block.getBaseColor() != null && border != null ){ template.fillStroke(); }else if( block.getBaseColor() != null ){ template.fill(); }else{ template.stroke(); } } cb.addTemplate( template, rect.getLeft(), rect.getBottom()); } }; }
public void convert(File pdfOut, float fontSize, boolean append) throws IOException, DocumentException, InvalidColourException { // First we write to tmp file then we copy to given destination, possibly appending File tmpPdf= Utils.createTempFile(pdfOut.getName(), ".pdf"); tmpPdf.deleteOnExit(); List<Paragraph> pdfLines= this.ansiFileToPdfParagraphs(fontSize); Rectangle pageSize = new Rectangle((float) (this.getMaxWidth() * 1.01), (float) (this.getMaxHeight())); int background256= Config.get256Color(ConfigKey.background); Color pageColor= Xterm256.xterm256ToColor(background256); pageSize.setBackgroundColor(new BaseColor(pageColor.getRed(), pageColor.getGreen(), pageColor.getBlue())); Document document = new Document(pageSize, 5f, 0f, 0f, 0f); //Document document = new Document(new Rectangle((float) (this.getMaxWidth() * 1.01), (float) (this.getMaxHeight())), 5f, 0f, 0f, 0f); PdfWriter.getInstance(document, new FileOutputStream(tmpPdf)); document.open(); for(Paragraph line : pdfLines){ document.add(line); } document.close(); if(append){ this.appendPdf(tmpPdf, pdfOut); } else { Files.move(Paths.get(tmpPdf.getAbsolutePath()), Paths.get(pdfOut.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); } }
public void start() { try { this.document = new Document(new Rectangle(this.bounds.getX() + this.bounds.getWidth(), this.bounds.getY() + this.bounds.getHeight()) ); PdfWriter writer = PdfWriter.getInstance(this.document, this.stream); this.document.open(); this.cb = writer.getDirectContent(); } catch(Throwable e){ TGErrorManager.getInstance(this.context).handleError(e); } }