List of usage examples for com.itextpdf.text.pdf PdfReader getPageSize
public Rectangle getPageSize(final PdfDictionary page)
From source file:gravabncertificado007.CarimboCertificado.java
public void aplicaCariboGedi(String BN, String caminhoarquivo) throws DocumentException, IOException, RuntimeException { PdfReader.unethicalreading = true;//from ww w .j a v a 2 s .c o m //Cria o reader para o primeiro PDF PdfReader reader = new PdfReader(caminhoarquivo); Rectangle psize = reader.getPageSize(1); float width = psize.getWidth(); float height = psize.getHeight(); Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-G.pdf")); document.open(); int i = 0; BN = BN.substring(BN.length() - 13, BN.length() - 4); PdfContentByte cb = writer.getDirectContent(); while (i < reader.getNumberOfPages()) { i++; document.newPage(); PdfContentByte under = writer.getDirectContentUnder(); PdfImportedPage page1 = writer.getImportedPage(reader, i); cb.addTemplate(page1, 0, i * 0.2f); BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 14); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " _________________ ", width / 6, 44, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 32, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 22, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |Copia Controlada |", width / 6, 28, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 16, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 12, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |_________________|", width / 6, 14, 0); cb.endText(); } document.close(); writer.close(); reader.close(); }
From source file:javaapplication1.JavaApplication1.java
public void parsePdf(String pdf, String txt) throws IOException { PdfReader reader = new PdfReader(pdf + ".pdf"); // PrintWriter out = new PrintWriter(new FileOutputStream(txt)); // Rectangle rect = new Rectangle(0,0, 300,800); // RenderFilter filter = new RegionTextRenderFilter(rect); // TextExtractionStrategy strategy; /* for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter); out.println(PdfTextExtractor.getTextFromPage(reader, i, strategy)); }*//*from w w w. j a va 2 s . co m*/ int pw, ph; Rectangle mrect; //reader = new PdfReader(pdf); String g = new String(); ArrayList<Integer> cutlist; int lastblank; int lastword; //int p=reader.getNumberOfPages(); int p = 1; double f; BufferedImage img; BufferedImage img1; for (int k = 1; k <= p; k++) { cutlist = new ArrayList<Integer>(); lastword = 0; lastblank = -1; mrect = reader.getPageSize(k); ph = (int) mrect.getHeight(); pw = (int) mrect.getWidth(); for (int i = 0; i <= (ph - fontchecksize); i += fontchecksize) { g = mycheckline(reader, ph, pw, i, k); if (g.isEmpty()) lastblank = i; else { // System.out.println(g); if (lastword == 0) { if (i > 2 * fontchecksize) cutlist.add(i - 2 * fontchecksize); else cutlist.add(0); lastword = i; } else if (g.matches("\\d+\\..*")) { cutlist.add(((lastword + i) / 2)); } lastword = i; } } if (lastword + 3 * fontchecksize < ph) { cutlist.add(lastword + 3 * fontchecksize); } else cutlist.add(ph - 1); // System.out.println("The arraylist contains the following elements: "+ cutlist); img = ImageIO.read(new File(txt + ".png")); //img1 = ImageIO.read(new File("prefix-1.png")); f = img.getHeight() / ph; //System.out.println(f); int s; // ImageIO.write(img.getSubimage(0,(int)(f*(84)),(int)(f*pw),(int)(f*(156-84))), "png", new File("7.png")); for (s = 0; s < (cutlist.size() - 1); s++) { // System.out.println(cutlist.get(s)); ImageIO.write( img.getSubimage(0, (int) (f * (cutlist.get(s))), (int) (f * pw), (int) (f * (cutlist.get(s + 1) - cutlist.get(s)))), "png", new File(txt + s + ".png")); } /* ImageIO.write(img.getSubimage(0,(int)(f*(84)),(int)(f*pw),(int)(f*(156-84))), "png", new File("7.png")); ImageIO.write(img.getSubimage(0,(int)(f*(156)),(int)(f*pw),(int)(f*(222-156))), "png", new File("8.png")); ImageIO.write(img1.getSubimage(0,(int)(f*(186)),(int)(f*pw),(int)(f*(225-186))), "png", new File("1.png")); ImageIO.write(img1.getSubimage(0,(int)(f*(225)),(int)(f*pw),(int)(f*(297-225))), "png", new File("2.png")); ImageIO.write(img1.getSubimage(0,(int)(f*(297)),(int)(f*pw),(int)(f*(339-297))), "png", new File("3.png")); ImageIO.write(img1.getSubimage(0,(int)(f*(339)),(int)(f*pw),(int)(f*(465-339))), "png", new File("4.png")); ImageIO.write(img1.getSubimage(0,(int)(f*(465)),(int)(f*pw),(int)(f*(585-465))), "png", new File("5.png")); ImageIO.write(img1.getSubimage(0,(int)(f*(585)),(int)(f*pw),(int)(f*(630-585))), "png", new File("6.png"));*/ } }
From source file:net.pflaeging.PortableSigner.PDFSigner.java
License:Open Source License
/** Creates a new instance of DoSignPDF */ public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password, Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment, String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin, float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException { try {/*from w w w . j a v a 2 s . c o m*/ //System.out.println("-> DoSignPDF <-"); //System.out.println("Eingabedatei: " + pdfInputFileName); //System.out.println("Ausgabedatei: " + pdfOutputFileName); //System.out.println("Signaturdatei: " + pkcs12FileName); //System.out.println("Signaturblock?: " + signText); //System.out.println("Sprache der Blocks: " + signLanguage); //System.out.println("Signaturlogo: " + sigLogo); System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin); Rectangle signatureBlock; java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2); pkcs12 = new GetPKCS12(pkcs12FileName, password); PdfReader reader = null; try { // System.out.println("Password:" + ownerPassword.toString()); if (ownerPassword == null) reader = new PdfReader(pdfInputFileName); else reader = new PdfReader(pdfInputFileName, ownerPassword); } catch (IOException e) { /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle( "net/pflaeging/PortableSigner/i18n").getString( "CouldNotBeOpened"), true, e.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("CouldNotBeOpened"), true, e.getLocalizedMessage()); } FileOutputStream fout = null; try { fout = new FileOutputStream(pdfOutputFileName); } catch (FileNotFoundException e) { /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"), true, e.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("CouldNotBeWritten"), true, e.getLocalizedMessage()); } PdfStamper stp = null; try { Date datum = new Date(System.currentTimeMillis()); int pages = reader.getNumberOfPages(); Rectangle size = reader.getPageSize(pages); stp = PdfStamper.createSignature(reader, fout, '\0', null, true); HashMap<String, String> pdfInfo = reader.getInfo(); // thanks to Markus Feisst String pdfInfoProducer = ""; if (pdfInfo.get("Producer") != null) { pdfInfoProducer = pdfInfo.get("Producer").toString(); pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")"; } else { pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")"; } pdfInfo.put("Producer", pdfInfoProducer); //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString()); stp.setMoreInfo(pdfInfo); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XmpWriter xmp = new XmpWriter(baos, pdfInfo); xmp.close(); stp.setXmpMetadata(baos.toByteArray()); if (signText) { String greet, signator, datestr, ca, serial, special, note, urn, urnvalue; int specialcount = 0; int sigpage; int rightMarginPT, leftMarginPT; float verticalPositionPT; ResourceBundle block = ResourceBundle .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage); greet = block.getString("greeting"); signator = block.getString("signator"); datestr = block.getString("date"); ca = block.getString("issuer"); serial = block.getString("serial"); special = block.getString("special"); note = block.getString("note"); urn = block.getString("urn"); urnvalue = block.getString("urnvalue"); //sigcomment = block.getString(signLanguage + "-comment"); // upper y float topy = size.getTop(); System.err.println("Top: " + topy * ptToCm); // right x float rightx = size.getRight(); System.err.println("Right: " + rightx * ptToCm); if (!noExtraPage) { sigpage = pages + 1; stp.insertPage(sigpage, size); // 30pt left, 30pt right, 20pt from top rightMarginPT = 30; leftMarginPT = 30; verticalPositionPT = topy - 20; } else { if (signLastPage) { sigpage = pages; } else { sigpage = 1; } System.err.println("Page: " + sigpage); rightMarginPT = Math.round(rightMargin / ptToCm); leftMarginPT = Math.round(leftMargin / ptToCm); verticalPositionPT = topy - Math.round(verticalPos / ptToCm); } if (!GetPKCS12.atEgovOID.equals("")) { specialcount = 1; } PdfContentByte content = stp.getOverContent(sigpage); float[] cellsize = new float[2]; cellsize[0] = 100f; // rightx = width of page // 60 = 2x30 margins // cellsize[0] = description row // cellsize[1] = 0 // 70 = logo width cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70; // Pagetable = Greeting, signatureblock, comment // sigpagetable = outer table // consist: greetingcell, signatureblock , commentcell PdfPTable signatureBlockCompleteTable = new PdfPTable(2); PdfPTable signatureTextTable = new PdfPTable(2); PdfPCell signatureBlockHeadingCell = new PdfPCell( new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12)))); signatureBlockHeadingCell.setPaddingBottom(5); signatureBlockHeadingCell.setColspan(2); signatureBlockHeadingCell.setBorderWidth(0f); signatureBlockCompleteTable.addCell(signatureBlockHeadingCell); // inner table start // Line 1 signatureTextTable.addCell( new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell( new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10)))); // Line 2 signatureTextTable.addCell( new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell( new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10)))); // Line 3 signatureTextTable.addCell( new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell( new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10)))); // Line 4 signatureTextTable.addCell( new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell(new Paragraph( new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10)))); // Line 5 if (specialcount == 1) { signatureTextTable.addCell(new Paragraph( new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell(new Paragraph( new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10)))); } signatureTextTable.addCell( new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10)))); signatureTextTable.setTotalWidth(cellsize); System.err.println( "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm); // inner table end signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); Image logo; // System.out.println("Logo:" + sigLogo + ":"); if (sigLogo == null || "".equals(sigLogo)) { logo = Image.getInstance( getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png")); } else { logo = Image.getInstance(sigLogo); } PdfPCell logocell = new PdfPCell(); logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); logocell.setImage(logo); signatureBlockCompleteTable.addCell(logocell); PdfPCell incell = new PdfPCell(signatureTextTable); incell.setBorderWidth(0f); signatureBlockCompleteTable.addCell(incell); PdfPCell commentcell = new PdfPCell( new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10)))); PdfPCell notecell = new PdfPCell( new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); //commentcell.setPaddingTop(10); //commentcell.setColspan(2); // commentcell.setBorderWidth(0f); if (!sigComment.equals("")) { signatureBlockCompleteTable.addCell(notecell); signatureBlockCompleteTable.addCell(commentcell); } float[] cells = { 70, cellsize[0] + cellsize[1] }; signatureBlockCompleteTable.setTotalWidth(cells); System.err.println( "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm); signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT, verticalPositionPT, content); System.err.println( "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm); signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20, topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20); // ////// // AcroFields af = reader.getAcroFields(); // ArrayList names = af.getSignatureNames(); // for (int k = 0; k < names.size(); ++k) { // String name = (String) names.get(k); // System.out.println("Signature name: " + name); // System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name)); // System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions()); // PdfPKCS7 pk = af.verifySignature(name); // X509Certificate tempsigner = pk.getSigningCertificate(); // Calendar cal = pk.getSignDate(); // Certificate pkc[] = pk.getCertificates(); // java.util.ResourceBundle tempoid = // java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID"); // String tmpEgovOID = ""; // // for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) { // String element = o.nextElement(); // // System.out.println(element + ":" + oid.getString(element)); // if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) { // if (!tmpEgovOID.equals("")) { // tmpEgovOID += ", "; // } // tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")"; // } // } // //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate())); // System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString()); // System.out.println("\tDatum: " + cal.getTime().toString()); // System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString()); // System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber()); // if (!tmpEgovOID.equals("")) { // System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID); // } // System.out.println("\n"); // System.out.println("\tDocument modified: " + !pk.verify()); //// Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal); //// if (fails == null) { //// System.out.println("\tCertificates verified against the KeyStore"); //// } else { //// System.out.println("\tCertificate failed: " + fails[1]); //// } // } // // ////// } else { signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition } PdfSignatureAppearance sap = stp.getSignatureAppearance(); // sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, // PdfSignatureAppearance.WINCER_SIGNED ); sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null); sap.setReason(signReason); sap.setLocation(signLocation); // if (signText) { // sap.setVisibleSignature(signatureBlock, // pages + 1, "PortableSigner"); // } if (finalize) { sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); } else { sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED); } stp.close(); /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"), false, ""); */ } catch (Exception e) { /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage()); } } catch (KeyStoreException kse) { /* MODIFY BY: Denis Torresan Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage()); } }
From source file:nz.ac.waikato.cms.doc.OverlayFilename.java
License:Open Source License
/** * Performs the overlay./*from w ww . j a v a 2 s . c o m*/ * * @param input the input file/dir * @param output the output file/dir * @param vpos the vertical position * @param hpos the horizontal position * @param stripPath whether to strip the path * @param stripExt whether to strip the extension * @param pages the array of pages (1-based) to add the overlay to, null for all * @param evenPages whether to enforce even pages in the document * @return true if successfully overlay */ public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt, int[] pages, boolean evenPages) { PdfReader reader; PdfStamper stamper; FileOutputStream fos; PdfContentByte canvas; int i; String text; int numPages; File tmpFile; Document document; PdfWriter writer; PdfImportedPage page; PdfContentByte cb; reader = null; stamper = null; fos = null; numPages = -1; try { reader = new PdfReader(input.getAbsolutePath()); fos = new FileOutputStream(output.getAbsolutePath()); stamper = new PdfStamper(reader, fos); numPages = reader.getNumberOfPages(); if (pages == null) { pages = new int[reader.getNumberOfPages()]; for (i = 0; i < pages.length; i++) pages[i] = i + 1; } if (stripPath) text = input.getName(); else text = input.getAbsolutePath(); if (stripExt) text = text.replaceFirst("\\.[pP][dD][fF]$", ""); for (i = 0; i < pages.length; i++) { canvas = stamper.getOverContent(pages[i]); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f); } } catch (Exception e) { System.err.println("Failed to process " + input + ":"); e.printStackTrace(); return false; } finally { try { if (stamper != null) stamper.close(); } catch (Exception e) { // ignored } try { if (reader != null) reader.close(); } catch (Exception e) { // ignored } try { if (fos != null) { fos.flush(); fos.close(); } } catch (Exception e) { // ignored } } // enforce even pages? if (evenPages && (numPages > 0) && (numPages % 2 == 1)) { reader = null; fos = null; writer = null; tmpFile = new File(output.getAbsolutePath() + "tmp"); try { if (!output.renameTo(tmpFile)) { System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!"); return false; } reader = new PdfReader(tmpFile.getAbsolutePath()); document = new Document(reader.getPageSize(1)); fos = new FileOutputStream(output.getAbsoluteFile()); writer = PdfWriter.getInstance(document, fos); document.open(); document.addCreationDate(); document.addAuthor(System.getProperty("user.name")); cb = writer.getDirectContent(); for (i = 0; i < reader.getNumberOfPages(); i++) { page = writer.getImportedPage(reader, i + 1); document.newPage(); cb.addTemplate(page, 0, 0); } document.newPage(); document.add(new Paragraph(" ")); // fake content document.close(); } catch (Exception e) { System.err.println("Failed to process " + tmpFile + ":"); e.printStackTrace(); return false; } finally { try { if (fos != null) { fos.flush(); fos.close(); } } catch (Exception e) { // ignored } try { if (reader != null) reader.close(); } catch (Exception e) { // ignored } try { if (writer != null) writer.close(); } catch (Exception e) { // ignored } if (tmpFile.exists()) { try { tmpFile.delete(); } catch (Exception e) { // ignored } } } } return true; }
From source file:nz.ac.waikato.cms.doc.SimplePDFOverlay.java
License:Open Source License
/** * Applies the instructions to the input PDF. * * @return null if successful, otherwise error message *///from ww w . j a va2 s .c om public String execute() { String result; String line; BufferedReader breader; FileReader freader; int i; int lineNo; String units; int pageNo; PdfReader reader; PdfStamper stamper; PdfContentByte cb; ColumnText ct; Font font; String[] parts; StringBuilder text; result = null; freader = null; breader = null; try { reader = new PdfReader(new FileInputStream(m_Pdf.getAbsolutePath())); stamper = new PdfStamper(reader, new FileOutputStream(m_Output.getAbsolutePath())); freader = new FileReader(m_Instructions); breader = new BufferedReader(freader); lineNo = 0; units = "pt"; pageNo = 1; cb = stamper.getOverContent(pageNo); font = null; while ((line = breader.readLine()) != null) { lineNo++; if (line.trim().startsWith(PREFIX_COMMENT)) continue; if (line.trim().length() == 0) continue; if (line.startsWith(PREFIX_UNITS)) { units = line.substring(PREFIX_UNITS.length()).trim().toLowerCase(); } else if (line.startsWith(PREFIX_PAGE)) { pageNo = Integer.parseInt(line.substring(PREFIX_PAGE.length()).trim()); cb = stamper.getOverContent(pageNo); } else if (line.startsWith(PREFIX_FONT)) { parts = line.substring(PREFIX_FONT.length()).trim().split(" "); if (parts.length == 3) font = FontFactory.getFont(parts[0], Float.parseFloat(parts[1]), new BaseColor(parseColor(parts[2]).getRGB())); else m_Logger.warning("Font instruction not in expected format (" + FORMAT_FONT + "):\n" + line); } else if (line.startsWith(PREFIX_TEXT)) { parts = line.substring(PREFIX_TEXT.length()).trim().split(" "); if (parts.length >= 7) { ct = new ColumnText(cb); ct.setSimpleColumn(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // llx parseLocation(parts[1], reader.getPageSize(pageNo).getHeight(), units), // lly parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // urx parseLocation(parts[3], reader.getPageSize(pageNo).getHeight(), units), // ury Float.parseFloat(parts[4]), // leading parseAlignment(parts[5])); // alignment text = new StringBuilder(); for (i = 6; i < parts.length; i++) { if (text.length() > 0) text.append(" "); text.append(parts[i]); } if (font == null) ct.setText(new Phrase(text.toString())); else ct.setText(new Phrase(text.toString(), font)); ct.go(); } else { m_Logger.warning("Text instruction not in expected format (" + FORMAT_TEXT + "):\n" + line); } } else if (line.startsWith(PREFIX_LINE)) { parts = line.substring(PREFIX_LINE.length()).trim().split(" "); if (parts.length >= 6) { cb.saveState(); cb.setLineWidth(Float.parseFloat(parts[4])); // line width cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // color cb.moveTo(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units)); // y cb.lineTo(parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // w parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units)); // h cb.stroke(); cb.restoreState(); } else { m_Logger.warning("Line instruction not in expected format (" + FORMAT_LINE + "):\n" + line); } } else if (line.startsWith(PREFIX_RECT)) { parts = line.substring(PREFIX_RECT.length()).trim().split(" "); if (parts.length >= 6) { cb.saveState(); cb.rectangle(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units), // y parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // w parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units) // h ); cb.setLineWidth(Float.parseFloat(parts[4])); // line width cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // stroke if (parts.length >= 7) { cb.setColorFill(new BaseColor(parseColor(parts[6]).getRGB())); // fill cb.fillStroke(); } else { cb.stroke(); } cb.restoreState(); } else { m_Logger.warning( "Rectangle instruction not in expected format (" + FORMAT_RECT + "):\n" + line); } } else if (line.startsWith(PREFIX_OVAL)) { parts = line.substring(PREFIX_OVAL.length()).trim().split(" "); if (parts.length >= 6) { cb.saveState(); cb.ellipse(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x1 parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units), // y1 parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // x2 parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units) // y2 ); cb.setLineWidth(Float.parseFloat(parts[4])); // line width cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // stroke if (parts.length >= 7) { cb.setColorFill(new BaseColor(parseColor(parts[6]).getRGB())); // fill cb.fillStroke(); } else { cb.stroke(); } cb.restoreState(); } else { m_Logger.warning("Oval instruction not in expected format (" + FORMAT_OVAL + "):\n" + line); } } else { m_Logger.warning("Unknown command on line #" + lineNo + ":\n" + line); } } stamper.close(); } catch (Exception e) { result = "Failed to process!\n" + Utils.throwableToString(e); } finally { FileUtils.closeQuietly(breader); FileUtils.closeQuietly(freader); } return result; }
From source file:org.gmdev.pdftrick.engine.MergeFiles.java
License:Open Source License
/** * Materially multiple pdf files are written merged file on a disk * @param list//from ww w . ja v a 2 s .c om * @param outputStream * @throws DocumentException * @throws IOException */ private void doMerge(List<StreamPwdContainer> list, OutputStream outputStream) throws DocumentException, IOException { HashMap<Integer, String> rotationFromPages = factory.getRotationFromPages(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); int z = 0; for (StreamPwdContainer boom : list) { InputStream in = boom.getIn(); PdfReader reader = null; if (!boom.getPwd().equalsIgnoreCase("")) { reader = new PdfReader(in, boom.getPwd().getBytes()); } else { reader = new PdfReader(in); } for (int i = 1; i <= reader.getNumberOfPages(); i++) { z++; int rotation = reader.getPageRotation(i); //set size Rectangle pageSize_ = reader.getPageSize(i); Rectangle pageSize = null; if (rotation == 270 || rotation == 90) { pageSize = new Rectangle(pageSize_.getHeight(), pageSize_.getWidth()); } else { pageSize = pageSize_; } document.setPageSize(pageSize); writer.setCropBoxSize(pageSize); document.newPage(); // import the page from source pdf PdfImportedPage page = writer.getImportedPage(reader, i); // add the page to the destination pdf if (rotation == 270) { cb.addTemplate(page, 0, 1.0f, -1.0f, 0, reader.getPageSizeWithRotation(i).getWidth(), 0); rotationFromPages.put(z, "" + rotation); } else if (rotation == 180) { cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0); rotationFromPages.put(z, "" + rotation); } else if (rotation == 90) { cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); rotationFromPages.put(z, "" + rotation); } else { cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } in.close(); } outputStream.flush(); document.close(); outputStream.close(); }
From source file:org.sejda.impl.itext5.component.AbstractPdfCopier.java
License:Open Source License
public void addBlankPage(PdfReader reader) throws TaskException { try {//from www. j a v a 2 s .c o m pdfCopy.addPage(reader.getPageSize(1), reader.getPageRotation(1)); numberOfCopiedPages++; } catch (DocumentException e) { throw new TaskException("Unable to add blank page.", e); } }
From source file:pl.edu.icm.cermine.structure.ITextCharacterExtractor.java
License:Open Source License
/** * Extracts text chunks from PDF using iText and stores them in BxDocument object. * Depending on parsed PDF, extracted text chunks may or may not be individual glyphs, * they correspond to single string operands of PDF's text-showing operators * (Tj, TJ, ' and ")./*from www. ja v a 2s.c om*/ * @param stream PDF's stream * @return BxDocument containing pages with extracted chunks stored as BxChunk lists * @throws AnalysisException AnalysisException */ @Override public BxDocument extractCharacters(InputStream stream) throws AnalysisException { try { BxDocumentCreator documentCreator = new BxDocumentCreator(); PdfReader reader = new PdfReader(stream); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(documentCreator); for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) { if (frontPagesLimit > 0 && backPagesLimit > 0 && pageNumber > frontPagesLimit && pageNumber < reader.getNumberOfPages() - 1 - backPagesLimit) { continue; } documentCreator.processNewBxPage(reader.getPageSize(pageNumber)); PdfDictionary resources = reader.getPageN(pageNumber).getAsDict(PdfName.RESOURCES); processAlternativeFontNames(resources); processAlternativeColorSpace(resources); processor.reset(); processor.processContent(ContentByteUtils.getContentBytesForPage(reader, pageNumber), resources); TimeoutRegister.get().check(); } BxDocument doc = filterComponents(removeDuplicateChunks(documentCreator.document)); if (doc.getFirstChild() == null) { throw new AnalysisException("Document contains no pages"); } return doc; } catch (InvalidPdfException ex) { throw new AnalysisException("Invalid PDF file", ex); } catch (IOException ex) { throw new AnalysisException("Cannot extract characters from PDF file", ex); } }
From source file:valstreamtools.ValStrSplitPage.java
private void splitDocument(String[] args) throws IOException, DocumentException { /**// w w w . j a v a 2s . com * int splitNo = 4; String inputFileName = * "C:\\tmp\\valuestream_export_input_2015-03-03-22-18-37.pdf"; String * outputFileName = "C:\\tmp\\valuestream_export_op_2015-03-03-22-18-37.pdf";* */ int splitNo = Integer.parseInt(args[0]); String inputFileName = args[1]; if (splitNo > 1) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String splitOutFileName = "/var/tmp/PDF_SPLIT_" + sdf.format(new Date()) + ".pdf"; PdfReader reader = new PdfReader(inputFileName); Rectangle pagesize = reader.getPageSize(1); float pageHeight = pagesize.getHeight(); float newpagewidth = (pagesize.getWidth() / splitNo); Rectangle newPapeSize = new Rectangle(0, 0, newpagewidth, pageHeight); Document document = new Document(newPapeSize); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(splitOutFileName)); document.open(); int pageNos = reader.getNumberOfPages(); PdfContentByte content = writer.getDirectContent(); for (int i = 1; i <= pageNos; i++) { PdfImportedPage page = writer.getImportedPage(reader, i); if (i > 1) {// In case of a new inpit page, need to create this. document.newPage(); } for (int j = 0; j < splitNo; j++) { if (j == 0) {//This condition is used to skip the adding of new page. content.addTemplate(page, 0, 0); } else { document.newPage(); content.addTemplate(page, (-1 * j * newpagewidth), 0); } } } document.close(); reader.close(); createPageNo(splitOutFileName, args[2], pageHeight); File f = new File(splitOutFileName); if (f.exists()) { f.delete(); } } else { PdfReader reader = new PdfReader(inputFileName); float pageHeight = reader.getPageSize(1).getHeight(); reader.close(); createPageNo(inputFileName, args[2], pageHeight); } }
From source file:watermarkpdf.FXMLDocumentController.java
@FXML private void handleButtonAction(ActionEvent event) throws DocumentException, IOException { if (tfPhrase.getLength() > 0) { lbl_Result.setText(""); PdfReader reader = new PdfReader(tf_PathFile.getText()); Rectangle mediabox = reader.getPageSize(1); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream( tf_PathFile.getText().substring(0, tf_PathFile.getLength() - 4) + "_out.pdf")); stamper.setRotateContents(false); BaseFont bf = BaseFont.createFont("TNR.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf); int iPos = tfPhrase.getText().indexOf('#'); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte canvas = stamper.getOverContent(i); if (iPos >= 0) { if (cbox_LU.isSelected()) { switch (i) { case 1: ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos - 5) + "? ? " + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); break; case 2: ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos - 5) + " ? " + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); break; default: ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos) + (i - 1) + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); }//from ww w . j ava 2 s . co m } else { if (i == 1) ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos - 5) + " ? " + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); else ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos) + (i) + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); } } else { ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(tfPhrase.getText(), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); } ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(tf_append.getText(), font), mediabox.getRight() * 2 / 3, mediabox.getTop() - 20, 0); } stamper.close(); reader.close(); if (tf_PagePrint.getLength() > 0) { reader = new PdfReader( tf_PathFile.getText().substring(0, tf_PathFile.getLength() - 4) + "_out.pdf"); reader.selectPages(tf_PagePrint.getText()); stamper = new PdfStamper(reader, new FileOutputStream( tf_PathFile.getText().substring(0, tf_PathFile.getLength() - 4) + "_out_cut.pdf")); stamper.close(); reader.close(); } lbl_Result.setText(" "); } }