public List<byte[]> split(byte[] input) throws IOException, DocumentException { PdfReader pdfReader = new PdfReader(input); List<byte[]> pdfFiles = new ArrayList<>(); int pageCount = pdfReader.getNumberOfPages(); int pageIndex = 0; while (++pageIndex <= pageCount) { Document document = new Document(pdfReader.getPageSizeWithRotation(pageIndex)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PdfCopy pdfCopy = new PdfSmartCopy(document, byteArrayOutputStream); pdfCopy.setFullCompression(); PdfImportedPage pdfImportedPage = pdfCopy.getImportedPage(pdfReader, pageIndex); document.open(); pdfCopy.addPage(pdfImportedPage); document.close(); pdfCopy.close(); pdfFiles.add(byteArrayOutputStream.toByteArray()); } return pdfFiles; }
/** * <a href="http://itext.2136553.n4.nabble.com/trying-to-remove-a-signature-from-pdf-file-tt4660983.html"> * trying to remove a signature from pdf file * </a> * <br/> * <a href="http://itext.2136553.n4.nabble.com/attachment/4660983/0/PDFSignedFirmaCerta.pdf"> * PDFSignedFirmaCerta.pdf * </a> * <p> * Indeed, this code fails with a {@link NullPointerException}. The cause is that a dubious construct * created by the signature software then is processed by iText code not sufficiently defensively programmed: * The signature claims to have an annotation on a page but that page does claim not to have any anotations * at all. * </p> */ @Test public void testRemoveSignatureFromPDFSignedFirmaCerta() throws IOException, GeneralSecurityException, DocumentException { try ( InputStream inputStream = getClass().getResourceAsStream("PDFSignedFirmaCerta.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "PDFSignedFirmaCerta-withoutSig.pdf"))) { Provider provider = new BouncyCastleProvider(); Security.addProvider(provider); PdfReader reader = new PdfReader(inputStream, null); AcroFields af = reader.getAcroFields(); ArrayList<String> names = af.getSignatureNames(); for (String name : names) { System.out.println("Signature name: " + name); System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name)); PdfPKCS7 pk = af.verifySignature(name, provider.getName()); System.out.println("SignatureDate: " + pk.getSignDate()); System.out.println("Certificate: " + pk.getSigningCertificate()); System.out.println("Document modified: " + !pk.verify()); af.removeField(name); } PdfStamper stamper = new PdfStamper(reader, outputStream, '\0'); stamper.close(); } }
/** * <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(); } }
@FXML public void generateFileAction(ActionEvent actionEvent) { FileChooser saveChooser = new FileChooser(); Window stage = ((Node) actionEvent.getSource()).getScene().getWindow(); saveChooser.setTitle("Zapisz plik"); saveChooser.setInitialDirectory(new File(System.getProperty("user.home"))); saveChooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("PDF file", "*.pdf")); saveChooser.setInitialFileName("faktura.pdf"); File file = saveChooser.showSaveDialog(stage); if (file != null) { try { updateData(); model.setInvoiceData(invoiceData); model.setReceiverData(receiverData); model.setSenderData(senderData); model.generatePDF(file); } catch (IOException | DocumentException e) { Dialog dialog = new Dialog<>(); dialog.getDialogPane().getButtonTypes().add(new ButtonType("Ok", ButtonBar.ButtonData.OK_DONE)); dialog.setContentText("Wystąpił błąd podczas próby zapisu"); dialog.showAndWait(); } } }
/** * */ @Override public void exportInnertion(OutputStream servletOut, List header, List data) throws IOException { // step 1 Document document = new Document(); // step 2 PdfWriter writer; try { writer = PdfWriter.getInstance(document, servletOut); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } // step 3 document.open(); // step 4 XMLWorkerHelper.getInstance().parseXHtml(writer, document, new java.io.StringReader( HtmlExport.createHTML(header, data))); // step 5 document.close(); }
public File downloadNote(int noteId, String type, String leftPath)throws IOException, DocumentException { Note note = noteDao.getNoteById(noteId); String currentVersion = note.getHistory().get(note.getVersionPointer()); JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject(); String content = obj.get("content").getAsString(); String htmlPath = leftPath + "htmlTemp.html"; File file = new File(htmlPath); file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write("<body>" + content + "</body>"); writer.close(); if(type.equals("pdf")) { String pdfPath = leftPath + "pdfTemp.pdf"; File pdfFile = new File(pdfPath); exportUtil.htmlToPdf(htmlPath, pdfFile); file.delete(); file = pdfFile; } //default html return file; }
public File downloadNotebook(int notebookId, String type, String leftPath) throws IOException,DocumentException{ File tempDir = new File(leftPath + "tempDir"); String tempPath = leftPath + "tempDir/"; tempDir.mkdirs(); ArrayList<Integer> notes = notebookDao.getNotebookById(notebookId).getNotes(); for(int noteId : notes){ Note note = noteDao.getNoteById(noteId); String currentVersion = note.getHistory().get(note.getVersionPointer()); JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject(); String content = obj.get("content").getAsString(); String htmlPath = tempPath + noteId +".html"; File file = new File(htmlPath); file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write("<body>" + content + "</body>"); writer.close(); if(type.equals("pdf")) { String pdfPath = tempPath + noteId +".pdf"; File pdfFile = new File(pdfPath); exportUtil.htmlToPdf(htmlPath, pdfFile); file.delete(); } } return exportUtil.compressExe(tempDir, leftPath + "temp.zip"); }
private BaseFont getIdentityFont(String fontPath,ApplicationContext applicationContext) throws DocumentException,IOException { if(!fontPath.startsWith(ApplicationContext.CLASSPATH_URL_PREFIX)){ fontPath=ApplicationContext.CLASSPATH_URL_PREFIX+fontPath; } String fontName = fontPath; int lastSlashPos=fontPath.lastIndexOf("/"); if(lastSlashPos!=-1){ fontName = fontPath.substring(lastSlashPos+1,fontPath.length()); } if (fontName.toLowerCase().endsWith(".ttc")) { fontName = fontName + ",0"; } InputStream inputStream=null; try{ inputStream=applicationContext.getResource(fontPath).getInputStream(); byte[] bytes = IOUtils.toByteArray(inputStream); BaseFont baseFont = BaseFont.createFont(fontName, BaseFont.IDENTITY_H,BaseFont.EMBEDDED,true,bytes,null); baseFont.setSubset(true); return baseFont; }finally{ if(inputStream!=null)inputStream.close(); } }
static String writeJChartToFile(JFreeChart chart, File file, FileTypes fileType) throws IOException, DocumentException { String fileName = file.getPath(); switch (fileType) { case svg: Tools.exportChartAsSVG(chart, new Rectangle(1000, 1000), file); break; case pdf: Tools.exportChartAsPDF(chart, new Rectangle(500, 400), file); break; case jchart: break; case csv: Tools.exportChartAsCSV(chart, file); break; default: ChartUtilities.saveChartAsPNG(file, chart, 1000, 1000); break; } return fileName; }
private static void addTitlePage(Document document,Resolucion res) throws DocumentException { Paragraph preface = new Paragraph(); // We add one empty line addEmptyLine(preface, 1); // Lets write a big header preface.add(new Paragraph("Consejo Profesional de Informatica de Santiago del Estero", catFont)); addEmptyLine(preface, 1); // Will create: Report generated by: _name, _date preface.add(new Paragraph( "Comision Directiva del Consejo, " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ smallBold)); addEmptyLine(preface, 2); preface.add(new Paragraph("Resolucion N°"+res.getNumero_resolucion()+"", smallBold)); addEmptyLine(preface, 3); preface.add(new Paragraph("Esta Resolucion de tipo "+res.getTipo()+" formulada para notificar al socio con legajo: "+res.getLegajo_socio()+" de su actual estado como socio del Consejo.\n" + res.getDescripcion_solicitud()+" "+res.getDescripcion_resolucion()+" en la fecha "+res.getFecha(), cuerpo)); document.add(preface); // Start a new page document.newPage(); }
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 export(final TrpDoc doc, final String path) throws DocumentException, MalformedURLException, IOException, JAXBException, TransformerException { File altoOutputDir = createAltoOuputDir(doc, path); //TrpPdfDocument pdf = new TrpPdfDocument(pdfFile, useWordLevel); notifyObservers("Exporting Altos..."); setChanged(); for (int i = 0; i < doc.getPages().size(); i++) { logger.info("Processing page " + (i+1)); notifyObservers(Integer.valueOf(i+1)); setChanged(); TrpPage p = doc.getPages().get(i); //3rd parameter says 'splitLineIntoWords' File altoFile = exportAltoFile(p, altoOutputDir, false); //XslTransformer.transform(pc, PAGE_TO_ALTO_XSLT, pdfFile); } notifyObservers("Alto written at: " + path); setChanged(); logger.info("ALTO files written at: " + path); // return outputDir; }
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(); } }
public List<Votante> loadCenso() throws DocumentException, IOException{ File archivo = new File(ruta); if(archivo.exists()){ List<Votante> votantesLeidos = parserArchivo(archivo); List<Votante> votantes = new ArrayList<Votante>(); for(Votante votante : votantesLeidos){ votante.setContrasena(generadorContraseñas.generar(votante)); if(Comprobaciones.isVotanteCorreto(votante)){ generadorCartas.generarCarta(votante); votantes.add(votante); } } return votantes; } else{ rW.WriteReport(ruta, "no se encuentra el archivo"); return null; } }
@Test public void canProcessTracks() throws InvalidGenomicCoordsException, IOException, ClassNotFoundException, BamIndexNotFoundException, InvalidRecordException, SQLException, InvalidConfigException, InvalidCommandLineException, DocumentException, InvalidColourException{ new Config(null); GenomicCoords gc= new GenomicCoords("chr7:1-100", 80, null, null); List<String> genome= new ArrayList<String>(); genome.add("test_data/ear045.oxBS.actb.bam"); gc.setGenome(genome, true); GenomicCoordsHistory gch= new GenomicCoordsHistory(); gch.add(gc); TrackSet trackSet= new TrackSet(); trackSet.addTrackFromSource("test_data/hg19_genes.gtf.gz", gc, null); trackSet.addTrackFromSource("test_data/ear045.oxBS.actb.bam", gc, null); trackSet.addTrackFromSource("test_data/ear045.oxBS.actb.tdf", gc, null); TrackProcessor tp= new TrackProcessor(trackSet, gch); // tp.iterateTracks(); }
public List<Votante> loadCenso() throws DocumentException, IOException{ File archivo = new File(ruta); if(archivo.exists()){ List<Votante> votantesLeidos = parserArchivo(archivo); List<Votante> votantes = new ArrayList<Votante>(); for(Votante votante : votantesLeidos){ votante.setContrasena(generadorContraseñas.generar(votante)); if(Comprobaciones.isVotanteCorreto(votante)){ generadorCartas.generarCarta(votante); votantes.add(votante); } } return votantes; } else{ rW.writeReport(ruta, "no se encuentra el archivo"); return null; } }
private void addOfferInstances(List<OfferInstance> offerInstances, Document document, BaseFont bf) throws DocumentException { if(offerInstances.isEmpty()) { return; } document.add(new Paragraph("Wybrane oferty: ", new Font(bf, 12))); PdfPTable offerInstancesTable = new PdfPTable(3); offerInstancesTable.setWidthPercentage(100); offerInstancesTable.setSpacingBefore(18f); offerInstancesTable.setSpacingAfter(18f); createofferInstancesTableHeaders(offerInstancesTable); createofferInstancesTableContent(offerInstances, offerInstancesTable); document.add(offerInstancesTable); }
private static int determineFontSize( int pageDiagonalSize, int estimatedFontSize, LinkedHashSet<Integer> haltSet ) throws DocumentException, IOException{ if(haltSet.contains(estimatedFontSize)){ return estimatedFontSize; } int newPageDiagonalSize = pageDiagonalSize - getCornerPlacementDiagonal(estimatedFontSize); int a4WaterMarkSizePoints = (int) getWaterkmarkFont().getWidthPoint(digitalSignatureWatermarkText, estimatedFontSize); if(a4WaterMarkSizePoints > newPageDiagonalSize){ haltSet.add(estimatedFontSize); return determineFontSize(pageDiagonalSize, (estimatedFontSize - 1), haltSet); } else if(a4WaterMarkSizePoints < newPageDiagonalSize) { haltSet.add(estimatedFontSize); return determineFontSize(pageDiagonalSize, (estimatedFontSize + 1), haltSet); } else { return a4WaterMarkSizePoints; } }
/** * <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 indeed is a case which shows that glyphs are completely removed even if their * bounding box merely minutely intersects the redaction area. While not desired by * the OP, this is how <code>PdfCleanUp</code> works. * </p> * * @see #testRedactStrictForMayankPandey() * @see #testRedactStrictForMayankPandeyLarge() */ @Test public void testRedactLikeMayankPandey() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("Document.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Document-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfCleanUpProcessor cleaner= null; PdfStamper stamper = new PdfStamper(reader, result); stamper.setRotateContents(false); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); Rectangle rectangle = new Rectangle(380, 640, 430, 665); cleanUpLocations.add(new PdfCleanUpLocation(1, rectangle, BaseColor.BLACK)); cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
/** * <p> * These two methods ({@link #extractAttachmentsWithFolders(PdfReader, String)} and * {@link #extractAttachment(PdfReader, Map, PdfString, PdfDictionary)}) extend the * functionality of the OP's original code posted in his question. They extract files * with the folder structure. * </p> * <p> * The information concerning the portfolio folder structure is retrieved using * the method {@link #retrieveFolders(PdfReader, File)} and its helper method * {@link #collectFolders(Map, PdfDictionary, File)}. * </p> */ public static void extractAttachmentsWithFolders(PdfReader reader, String dir) throws IOException, DocumentException { File folder = new File(dir); folder.mkdirs(); Map<Integer, File> folders = retrieveFolders(reader, folder); PdfDictionary root = reader.getCatalog(); PdfDictionary names = root.getAsDict(PdfName.NAMES); System.out.println("" + names.getKeys().toString()); PdfDictionary embedded = names.getAsDict(PdfName.EMBEDDEDFILES); System.out.println("" + embedded.toString()); PdfArray filespecs = embedded.getAsArray(PdfName.NAMES); for (int i = 0; i < filespecs.size();) { extractAttachment(reader, folders, folder, filespecs.getAsString(i++), filespecs.getAsDict(i++)); } }
/** * <a href="https://stackoverflow.com/questions/44304695/itext-5-5-11-bold-text-looks-blurry-after-using-pdfcleanupprocessor"> * iText 5.5.11 - bold text looks blurry after using PdfCleanUpProcessor * </a> * <br/> * <a href="http://s000.tinyupload.com/index.php?file_id=52420782334200922303"> * before.pdf * </a> * <p> * Indeed, the observation by the OP can be reproduced. The issue has been introduced * into iText in commits d5abd23 and 9967627, both dated May 4th, 2015. * </p> */ @Test public void testRedactLikeTieco() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("before.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "before-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(0f, 0f, 595f, 680f))); PdfCleanUpProcessor cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
private void savePDF(File file) { setWorkingState(Messages.getString("BrissGUI.loadingPDF")); //$NON-NLS-1$ try { CropDefinition cropDefinition = CropDefinition.createCropDefinition(workingSet.getSourceFile(), file, workingSet.getClusterDefinition()); File result = DocumentCropper.crop(cropDefinition); if (result != null) { DesktopHelper.openFileWithDesktopApp(result); lastOpenDir = result.getParentFile(); } } catch (IOException | DocumentException | CropException e) { JOptionPane.showMessageDialog(this, e.getMessage(), Messages.getString("BrissGUI.croppingError"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ } finally { setIdleState(); //$NON-NLS-1$ } }
/** * This method creates a PDF with a single styled paragraph. */ static byte[] createSimpleTextPdf() throws DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); Paragraph paragraph = new Paragraph(); paragraph.add(new Phrase("Beware: ", new Font(FontFamily.HELVETICA, 12, Font.BOLDITALIC))); paragraph.add(new Phrase("The implementation of ", new Font(FontFamily.HELVETICA, 12, Font.ITALIC))); paragraph.add(new Phrase("MarginFinder", new Font(FontFamily.COURIER, 12, Font.ITALIC))); paragraph.add(new Phrase(" is far from optimal. It is not even correct as it includes all curve control points which is too much. Furthermore it ignores stuff like line width or wedge types. It actually merely is a proof-of-concept.", new Font(FontFamily.HELVETICA, 12, Font.ITALIC))); document.add(paragraph); document.close(); return baos.toByteArray(); }
@Test public void sign2274_2007_H_PROVISIONAL_multifield() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2274_2007_H_PROVISIONAL - multifield.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, "2274_2007_H_PROVISIONAL - multifield-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("IntSig1"); // 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); }
private void addTitlePage(Document document) throws DocumentException { addEmptyLine(document, 5); Paragraph title = new Paragraph("Data Dictionary by Arrah technology"); title.setAlignment(Element.ALIGN_CENTER); document.add(title); addEmptyLine(document, 1); Paragraph url = new Paragraph("http://sourceforge.net/projects/dataquality/"); url.setAlignment(Element.ALIGN_CENTER); document.add(url); addEmptyLine(document, 3); Paragraph rtime = new Paragraph("Report generated on: " + new Date()); rtime.setAlignment(Element.ALIGN_CENTER); document.add(rtime); document.newPage(); }
@Test public void signCertify2gNoAppend() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "2g-certified-noAppend.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER); // 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/30526254/sign-concatenated-pdf-in-append-mode-with-certified-no-changes-allowed"> * Sign concatenated PDF in append mode with CERTIFIED_NO_CHANGES_ALLOWED * </a> * <br> * <a href="https://www.dropbox.com/s/lea6r9fup6th44c/test_pdf.zip?dl=0">test_pdf.zip</a> * * {@link #signCertifyG()} certifies g.pdf, OK * {@link #sign2g()} merely signs 2g.pdf, OK * {@link #signCertify2gNoAppend()} certifies 2g.pdf but not in append mode, OK * {@link #tidySignCertify2g()} first tidies, then certifies 2g.pdf, OK * {@link #signCertify2g()} certifies 2g.pdf, Adobe says invalid * {@link #signCertify2gFix()} certifies 2g-fix.pdf, OK! * * 2g-fix.pdf is a patched version of 2g.pdf with a valid /Size trailer entry * and a valid, single-sectioned cross reference table */ @Test public void signCertifyG() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/g.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "g-certified.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
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); }
public void merge(OutputStream outputStream, Iterable<PdfReader> inputs) throws DocumentException, IOException { try { openDocument(outputStream); for (PdfReader reader: inputs) { merge(reader); } } finally { closeDocument(); } }
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(); }
/** * <a href="http://stackoverflow.com/questions/32818522/itextsharp-setvisiblesignature-not-working-as-expected"> * ITextSharp SetVisibleSignature not working as expected * </a> * <p> * The issue observed by the OP (user2699460) occurs since iText(Sharp) 5.5.7 * both of iText and iTextSharp. * </p> * <p> * The file signed in this sample, test-2-user2699460-signed.pdf, has been created * as intermediary result using a simplified version of the OP's c# code. * </p> */ @Test public void signTest_2_user2699460() throws IOException, DocumentException, GeneralSecurityException { String filepath = "src/test/resources/mkl/testarea/itext5/signature/test-2-user2699460.pdf"; String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; // Creating the reader and the stamper PdfReader reader = new PdfReader(filepath, null, true); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "test-2-user2699460-signed.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', RESULT_FOLDER, true); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature("Bunker"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); }
/** * 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(); }
/** * <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(); } }
/** * <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> * <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, cf. * {@link #testAddUnicodeStampEg_01()}. This test creates a new PDF with the same * font and chunk as stamped by the OP. Adobe Reader has no problem with it either. * </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 testCreateUnicodePdf() throws DocumentException, IOException { Document document = new Document(); try ( OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "unicodePdf.pdf")) ) { PdfWriter.getInstance(document, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); document.open(); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); document.add(p); document.close(); } }
@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/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(); } } }
/** * <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 on a even smaller page. * </p> */ @Test public void testMergeGrandizerFilesA5() 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(new RectangleReadOnly(595,421), 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-A5.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); } } }
/** * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-document-using-it"> * how to create a PDF and you then merge another pdf to the same document using itext * </a> * <p> * Testing the OP's method with <code>paginate</code> set to <code>true</code> * </p> */ @Test public void testAppendPDFsPaginate() throws IOException, DocumentException { try ( InputStream testA4Stream = getClass().getResourceAsStream("testA4.pdf"); InputStream fromStream = getClass().getResourceAsStream("from.pdf"); InputStream prefaceStream = getClass().getResourceAsStream("preface.pdf"); InputStream type3Stream = getClass().getResourceAsStream("Test_Type3_Problem.pdf"); FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfsPaginate.pdf")); ) { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, output); document.open(); document.add(new Paragraph("Some content to start with")); appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, document, null, true); document.close(); } }
/** * <a href="https://stackoverflow.com/questions/46204693/cant-get-itext-rectangle-to-work-correctly-with-annotations"> * Can't get itext Rectangle to work correctly with annotations * </a> * <p> * This test looks at a <b>Text</b> annotation added via a {@link Chunk} * as done by the OP. As this way of adding annotations resets the * annotation <b>Rect</b> to the bounding box of the rendered {@link Chunk}, * it is not really what the OP wants. * </p> */ @Test public void testAnnotationIconForTYD() throws FileNotFoundException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "annotationIcons.pdf"))); document.open(); // Not "new Rectangle(164, 190, 164, 110)" which would be empty Rectangle rect = new Rectangle(164, 190, 328, 300); // Annotation added like the OP does Chunk chunk_text = new Chunk("Let's test a Text annotation..."); chunk_text.setAnnotation(PdfAnnotation.createText(writer, rect, "Warning", "This is a Text annotation with Comment icon.", false, "Comment")); document.add(chunk_text); // Annotation added to the document without Chunk writer.addAnnotation(PdfAnnotation.createText(writer, rect, "Warning 2", "This is another Text annotation with Comment icon.", false, "Comment")); document.close(); }
@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); }