List of usage examples for com.lowagie.text.pdf PdfReader getPageSize
public Rectangle getPageSize(PdfDictionary page)
From source file:org.silverpeas.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file/* w ww . ja v a 2 s. c om*/ * @param pdfDestination the destination pdf file, with the image under or over content * @param isBackground indicates if image is addes under or over the content of the pdf source * file */ private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination, final boolean isBackground) { // Verify given arguments if (imageToAdd == null || !imageToAdd.isFile()) { throw new RuntimeException("The image file doesn't exist"); } else if (!FileUtil.isImage(imageToAdd.getPath())) { throw new RuntimeException("The picture to add is not an image file"); } PdfReader reader = null; try { // Get a reader of PDF content reader = new PdfReader(pdfSource); // Obtain the total number of pages int pdfNbPages = reader.getNumberOfPages(); PdfStamper stamper = new PdfStamper(reader, pdfDestination); // Load the image Image image = Image.getInstance(imageToAdd.getPath()); float imageWidth = image.getWidth(); float imageHeigth = image.getHeight(); // Adding the image on each page of the PDF for (int i = 1; i <= pdfNbPages; i++) { // Page sizes Rectangle rectangle = reader.getPageSize(i); // Compute the scale of the image float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100)); image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100))); // Setting the image position for the current page image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()), computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight())); // Adding image PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i) : stamper.getOverContent(i); imageContainer.addImage(image); } // End of the treatment : closing the stamper stamper.close(); } catch (Exception e) { SilverTrace.error("util", "PdfUtil.stamp", "EX_ERROR_PDF_ADD_WATERWARK", e); throw new RuntimeException("A problem has occured during the adding of an image into a pdf file", e); } finally { if (reader != null) { reader.close(); } } }
From source file:org.viafirma.util.QRCodeUtil.java
License:Apache License
/** * Genera un justificante de firma de un fichero pdf de entrada. * //from w ww . jav a 2s. com * @param input * Fichero pdf de entrada * @param texto * @param textoQR * @param codFirma * @param out * @throws ExcepcionErrorInterno */ public void firmarPDF(InputStream input, String texto, String texto2Line, String textoQR, String codFirma, OutputStream out) throws ExcepcionErrorInterno { // leemos el pdf utilizando iText. try { // Recuperamos el documento original PdfReader reader = new PdfReader(input); // Obtenemos el tamao de la pgina Rectangle pageSize = reader.getPageSize(1); // Creamos un nuevo documento del mismo tamao que el original Document document = new Document(pageSize); // creo una instancia para escritura en el documento PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); // insertamos la portada del documento que estamos firmando. float escala = (pageSize.getHeight() - 350) / pageSize.getHeight(); // Aadimos al documento la imagen de cabecera y de pie addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true, false); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage portada = writer.getImportedPage(reader, 1); cb.setRGBColorStroke(0xCC, 0xCC, 0xCC); cb.transform(AffineTransform.getTranslateInstance(document.leftMargin(), 210)); cb.transform(AffineTransform.getScaleInstance(escala, escala)); cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy); document.close(); out.close(); } catch (Exception e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } }
From source file:org.viafirma.util.QRCodeUtil.java
License:Apache License
/** * Genera un documento sellado en fichero pdf. * /*from w w w . j a v a 2s .c o m*/ * @param input * Fichero pdf de entrada * @param texto * @param textoQR * @param codFirma * @param out * @throws ExcepcionErrorInterno */ public void firmarPDFSellado(InputStream input, String texto, String texto2Line, String textoQR, String codFirma, OutputStream out) throws ExcepcionErrorInterno { // leemos el pdf utilizando iText. try { // Recuperamos el documento original PdfReader reader = new PdfReader(input); // Obtenemos el tamao de la pgina Rectangle pageSize = reader.getPageSize(1); // Creamos un nuevo documento del mismo tamao que el original Document document = new Document(pageSize); // creo una instancia para escritura en el documento PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); // Aadimos al documento la imagen de cabecera y de pie float altoCabeceraYPie = addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true, true); altoCabeceraYPie = altoCabeceraYPie + document.topMargin(); // insertamos la portada del documento que estamos firmando. float escala = (pageSize.getHeight() - altoCabeceraYPie) / pageSize.getHeight(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage portada = writer.getImportedPage(reader, 1); cb.setRGBColorStroke(0xCC, 0xCC, 0xCC); cb.transform(AffineTransform.getScaleInstance(escala, escala)); cb.transform(AffineTransform.getTranslateInstance(document.leftMargin() * 2.5, ALTO_ETIQUETA + document.topMargin())); cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy); document.close(); out.close(); } catch (Exception e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } }
From source file:oscar.eform.util.EFormPDFServlet.java
License:Open Source License
/** * the form txt file has lines in the form: * * For Checkboxes:// ww w . ja v a 2 s . c om * ie. ohip : left, 76, 193, 0, BaseFont.ZAPFDINGBATS, 8, \u2713 * requestParamName : alignment, Xcoord, Ycoord, 0, font, fontSize, textToPrint[if empty, prints the value of the request param] * NOTE: the Xcoord and Ycoord refer to the bottom-left corner of the element * * For single-line text: * ie. patientCity : left, 242, 261, 0, BaseFont.HELVETICA, 12 * See checkbox explanation * * For multi-line text (textarea) * ie. aci : left, 20, 308, 0, BaseFont.HELVETICA, 8, _, 238, 222, 10 * requestParamName : alignment, bottomLeftXcoord, bottomLeftYcoord, 0, font, fontSize, _, topRightXcoord, topRightYcoord, spacingBtwnLines * *NOTE: When working on these forms in linux, it helps to load the PDF file into gimp, switch to pt. coordinate system and use the mouse to find the coordinates. *Prepare to be bored! * * * @throws Exception */ protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx, int multiple) throws Exception { // added by vic, hsfo if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) return generateHsfoRxPDF(req); String suffix = (multiple > 0) ? String.valueOf(multiple) : ""; ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, baosPDF); String title = req.getParameter("__title" + suffix) != null ? req.getParameter("__title" + suffix) : "Unknown"; String template = req.getParameter("__template" + suffix) != null ? req.getParameter("__template" + suffix) + ".pdf" : ""; int numPages = 1; String pages = req.getParameter("__numPages" + suffix); if (pages != null) { numPages = Integer.parseInt(pages); } //load config files Properties[] printCfg = loadPrintCfg(req, suffix); Properties[][] graphicCfg = loadGraphicCfg(req, suffix, numPages); int cfgFileNo = printCfg == null ? 0 : printCfg.length; Properties props = new Properties(); getPrintPropValues(props, req, suffix); Properties measurements = new Properties(); //initialise measurement collections = a list of pages sections measurements List<List<List<String>>> xMeasurementValues = new ArrayList<List<List<String>>>(); List<List<List<String>>> yMeasurementValues = new ArrayList<List<List<String>>>(); for (int idx = 0; idx < numPages; ++idx) { MiscUtils.getLogger().debug("Adding page " + idx); xMeasurementValues.add(new ArrayList<List<String>>()); yMeasurementValues.add(new ArrayList<List<String>>()); } saveMeasurementValues(measurements, props, req, numPages, xMeasurementValues, yMeasurementValues); addDocumentProps(document, title, props); // create a reader for a certain document String propFilename = OscarProperties.getInstance().getProperty("eform_image", "") + "/" + template; PdfReader reader = null; try { reader = new PdfReader(propFilename); log.debug("Found template at " + propFilename); } catch (Exception dex) { log.warn("Cannot find template at : " + propFilename); } // retrieve the total number of pages int n = reader.getNumberOfPages(); // retrieve the size of the first page Rectangle pSize = reader.getPageSize(1); float height = pSize.getHeight(); PdfContentByte cb = writer.getDirectContent(); int i = 0; while (i < n) { document.newPage(); i++; PdfImportedPage page1 = writer.getImportedPage(reader, i); cb.addTemplate(page1, 1, 0, 0, 1, 0, 0); cb.setRGBColorStroke(0, 0, 255); // LEFT/CENTER/RIGHT, X, Y, if (i <= cfgFileNo) { writeContent(printCfg[i - 1], props, measurements, height, cb); } //end if there are print properties //graphic Properties[] tempPropertiesArray; if (i <= graphicCfg.length) { tempPropertiesArray = graphicCfg[i - 1]; MiscUtils.getLogger().debug("Plotting page " + i); } else { tempPropertiesArray = null; MiscUtils.getLogger().debug("Skipped Plotting page " + i); } //if there are properties to plot if (tempPropertiesArray != null) { MiscUtils.getLogger().debug("TEMP PROP LENGTH " + tempPropertiesArray.length); for (int k = 0; k < tempPropertiesArray.length; k++) { //initialise with measurement values which are mapped to config file by form get graphic function List<String> xDate, yHeight; if (xMeasurementValues.get(i - 1).size() > k && yMeasurementValues.get(i - 1).size() > k) { xDate = new ArrayList<String>(xMeasurementValues.get(i - 1).get(k)); yHeight = new ArrayList<String>(yMeasurementValues.get(i - 1).get(k)); } else { xDate = new ArrayList<String>(); yHeight = new ArrayList<String>(); } plotProperties(tempPropertiesArray[k], props, xDate, yHeight, height, cb, (k % 2 == 0)); } } //end: if there are properties to plot } } finally { if (document.isOpen()) document.close(); if (writer != null) writer.close(); } return baosPDF; }
From source file:questions.stamppages.IncreaseMediabox.java
public static void main(String[] args) { try {/*from w w w .j a v a 2s. co m*/ PdfDictionary pageDict; PdfReader reader = new PdfReader(RESOURCE); int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { Rectangle rect = reader.getPageSize(i); pageDict = reader.getPageN(i); PdfRectangle pdfrect = new PdfRectangle(rect.getLeft(-36), rect.getBottom(-36), rect.getRight(-36), rect.getTop(-36)); pageDict.put(PdfName.MEDIABOX, pdfrect); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:questions.stamppages.StampAndAddColumns.java
public static void main(String[] args) { try {/*from www . j a v a 2s. c om*/ PdfReader reader = new PdfReader(RESOURCE); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); AcroFields form = stamper.getAcroFields(); form.setField("Who", "world"); ColumnText ct = new ColumnText(stamper.getOverContent(1)); String line; Phrase p; BufferedReader br = new BufferedReader(new FileReader(TXT)); while ((line = br.readLine()) != null) { p = new Phrase(line + "\n"); ct.addText(p); } int status = ColumnText.START_COLUMN; ct.setSimpleColumn(100, 700, 495, 100); status = ct.go(); int pageCt = 1; while (ColumnText.hasMoreText(status)) { stamper.insertPage(++pageCt, reader.getPageSize(1)); ct.setYLine(700); ct.setCanvas(stamper.getOverContent(pageCt)); status = ct.go(); } stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:si.vsrs.cif.svev.example.utils.PDFSignature.java
License:EUPL
public File signPDF(File document, InputStream keystore, String password, String keyPassord, String keystoreType, String alias, boolean bshowVisualization) { if (document == null || !document.exists()) { throw new RuntimeException("Error reading pdf"); }/*from w ww . j a v a2 s . c o m*/ String name = document.getName(); String substring = name.substring(0, name.lastIndexOf(".")); File outputDocument = new File(document.getParent(), substring + "_signed.pdf"); try (FileInputStream fis = new FileInputStream(document); FileOutputStream fout = new FileOutputStream(outputDocument)) { KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keystore, password.toCharArray()); PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassord.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); X509Certificate xcert = (X509Certificate) chain[0]; PdfReader reader = new PdfReader(fis); char tmpPdfVersion = '\0'; // default version - the same as input final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, true); final PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("Testni podpis"); sap.setLocation("Maribor"); sap.setContact(xcert.getSubjectDN().getName()); // sap.setLayer2Text(""); // sap.setLayer4Text(""); sap.setAcro6Layers(true); // --:> Rectangle rc = reader.getPageSize(1); if (bshowVisualization) { sap.setVisibleSignature(new Rectangle(5, rc.getHeight() - 40, 240, rc.getHeight() - 5), 1, null); } final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); final int contentEstimated = 15000; final HashMap<PdfName, Integer> exc = new HashMap<>(); exc.put(PdfName.CONTENTS, contentEstimated * 2 + 2); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA-256", null, false); InputStream data = sap.getRangeStream(); final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null); sgn.update(sh, 0, sh.length); byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null, null); byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | DocumentException | InvalidKeyException | NoSuchProviderException | SignatureException ex) { throw new RuntimeException(ex.getMessage(), ex); } return outputDocument; }