List of usage examples for com.itextpdf.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:net.digitstar.vanadio.AbstractReportPdf.java
License:Apache License
private void closeDocument(Document document, ByteArrayOutputStream baos, OutputStream out) { if (document != null) { document.close();// www. ja v a2s.c o m PdfStamper writer = null; try { PdfReader reader = new PdfReader(baos.toByteArray()); writer = new PdfStamper(reader, out); afterCloseDocument(document, reader, writer); } catch (IOException e) { /**/ } catch (DocumentException e) { /**/ } finally { if (writer != null) try { writer.close(); } catch (DocumentException e) { /**/} catch (IOException e) { /**/} } } }
From source file:net.ionescu.jhocr2pdf.Jhocr2pdf.java
License:Open Source License
/** * @param args/*from w w w .ja v a 2s . c o m*/ * The arguments are: * [options] output_pdf * The name of the output PDF file with the added OCR information must be the last argument * Other * flags: * -i pdf_file PDF file containing the TIFF images * -hocr html_file hOCR file generated by Tesseract * -visible render the text above the image (mostry for debugging) * -font font_path path to the font file to use * -hocrnameformat string to use to construct the name of the hocr file depending on page number * * Usage example: * java -jar jhorc2pdf.jar -font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf -i input.pdf -hocr input.html output.pdf * * @throws SAXException * @throws IOException * @throws DocumentException */ public static void main(String[] args) throws SAXException, IOException, DocumentException { /* * process input parameters * * -visible -font font_path inputPDF inputOCR outputPDF */ boolean visible = false; String fontPath = null; String fileNameFormat = null; String inputPDF = null; String inputHOCR = null; String outputPDF = null; for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-")) { switch (args[i]) { case "-visible": visible = true; break; case "-font": fontPath = args[++i]; break; case "-hocrnameformat": fileNameFormat = args[++i]; break; case "-i": inputPDF = args[++i]; break; case "-hocr": inputHOCR = args[++i]; break; default: System.err.println("Invalid parameter: " + args[i]); System.exit(1); } } else { if (i < args.length - 1) { System.err.println("Ouput file name should be the last argument"); System.exit(1); } outputPDF = args[i]; } } log.fine("load the PDF file, initialize the Stamper"); PdfReader reader = new PdfReader(inputPDF); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPDF)); Map<String, String> info = reader.getInfo(); info.put("Title", new File(outputPDF).getName()); stamper.setMoreInfo(info); Jhocr2pdf ocrStamp = new Jhocr2pdf(stamper, visible, fontPath); if (null != fileNameFormat) { log.fine("iterate through all the pages looking for separate hocr files"); for (int i = 1, maxPages = reader.getNumberOfPages() + 1; i < maxPages; i++) { String hocrFileName = String.format(fileNameFormat, i); try { ocrStamp.parse(hocrFileName, i); } catch (SAXException saxException) { System.err.println("Error processing hocr file: " + hocrFileName); throw saxException; } } } else { ocrStamp.parse(inputHOCR, -1); } stamper.close(); }
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 www . j a v a 2s . com //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.// w ww . j a v a 2 s . co 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 w ww .jav a 2s. c o m*/ 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:om.edu.squ.squportal.portlet.tsurvey.dao.pdf.TeachingSurveyPdfImpl.java
License:Open Source License
/** * /* w ww .j ava2 s. c o m*/ * method name : getPdfSurveyAnalysis * @param object * @param semesterYear * @param questionByYear * @param questionSetNo * @param byos * @param inputStream * @param res * @return * @throws DocumentException * @throws IOException * TeachingSurveyPdfImpl * return type : OutputStream * * purpose : Generate PDF content * * Date : Mar 28, 2016 7:21:04 PM */ public OutputStream getPdfSurveyAnalysis(Object object, String semesterYear, String questionByYear, int questionSetNo, ByteArrayOutputStream byos, InputStream inputStream, ResourceResponse res) throws DocumentException, IOException { Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, BaseColor.BLACK); PdfReader pdfTemplate = new PdfReader(inputStream); PdfStamper pdfStamper = new PdfStamper(pdfTemplate, byos); Survey survey = (Survey) object; String sectionNos = ""; String seatsTaken = ""; DecimalFormat formatter = new DecimalFormat("###.##"); String RIGHT = Constants.RIGHT; String CENTER = Constants.CENTER; String LEFT = Constants.LEFT; pdfStamper.getAcroFields().setField("txtCourse", survey.getCourseCode() + " / " + survey.getCourseName()); pdfStamper.getAcroFields().setField("txtCollegeName", survey.getCollegeName()); for (SurveyResponse resp : survey.getSurveyResponses()) { sectionNos = sectionNos + resp.getSectionNo() + " "; seatsTaken = String.valueOf(resp.getSeatsTaken()); } pdfStamper.getAcroFields().setField("txtSectionNo", sectionNos); pdfStamper.getAcroFields().setField("txtDepartmentName", survey.getDepartmentName()); pdfStamper.getAcroFields().setField("txtEmpName", survey.getEmpName()); pdfStamper.getAcroFields().setField("txtStudentRegistered", seatsTaken); pdfStamper.getAcroFields().setField("txtSemesterYear", semesterYear); pdfStamper.getAcroFields().setGenerateAppearances(true); /* ****************** */ PdfPTable table = new PdfPTable(13); table.addCell(getPdfCell("", 2, 0, font, LEFT)); table.addCell(getPdfCell( UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.teaching.items", null), 2, 0, font, CENTER)); table.addCell( getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.number", null), 0, 6, font, CENTER)); table.addCell(getPdfCell( UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.percentage", null), 2, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.mean", null), 0, 4, font, CENTER)); table.addCell( getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree.strong", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree.strong", null), 0, 0, font, CENTER)); table.addCell( getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.applicable.not", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.total", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.sect", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.crs", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.dept", null), 0, 0, font, CENTER)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.col", null), 0, 0, font, CENTER)); /* ---------------------------------------------------------------------------- */ table.addCell(getPdfCell("", 0, 0, font)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.items", null), 0, 12, font, CENTER)); int cTotal = 0; float cPctVal = 0f; float cSectionMean = 0f; float cCourseMean = 0f; float cDepart = 0f; float cCollege = 0f; int rowCount = 0; for (SurveyResponse sures : survey.getSurveyResponses()) { for (Analysis analysis : sures.getAnalysisList()) { if (analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14") || analysis.getQuestion().equals(questionByYear)) { /*** First part ***/ table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font)); table.addCell( getPdfCell( UtilProperty.getMessage("prop.course.teaching.survey.analysis.set" + questionSetNo + ".question" + analysis.getQuestionLabel(), null), 0, 0, font, LEFT)); table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT)); cTotal = cTotal + analysis.getTotal(); cPctVal = cPctVal + analysis.getPercentageResponse(); cSectionMean = cSectionMean + analysis.getSectionMean(); cCourseMean = cCourseMean + analysis.getCollegeMean(); cDepart = cDepart + analysis.getDepartmentMean(); cCollege = cCollege + analysis.getCollegeMean(); rowCount = rowCount + 1; } } } /*** First part - Summary ***/ table.addCell(getPdfCell(String.valueOf(""), 0, 0, font)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(""), 0, 5, font)); table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell("", 0, 13, font)); table.addCell(getPdfCell("", 0, 0, font)); table.addCell( getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.teaching.items", null), 0, 12, font, LEFT)); cTotal = 0; cPctVal = 0f; cSectionMean = 0f; cCourseMean = 0f; cDepart = 0f; cCollege = 0f; rowCount = 0; for (SurveyResponse sures : survey.getSurveyResponses()) { for (Analysis analysis : sures.getAnalysisList()) { if (!(analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14") || analysis.getQuestion().equals(questionByYear))) { table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font)); table.addCell( getPdfCell( UtilProperty.getMessage("prop.course.teaching.survey.analysis.set" + questionSetNo + ".question" + analysis.getQuestionLabel(), null), 0, 0, font, LEFT)); table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT)); cTotal = cTotal + analysis.getTotal(); cPctVal = cPctVal + analysis.getPercentageResponse(); cSectionMean = cSectionMean + analysis.getSectionMean(); cCourseMean = cCourseMean + analysis.getCollegeMean(); cDepart = cDepart + analysis.getDepartmentMean(); cCollege = cCollege + analysis.getCollegeMean(); rowCount = rowCount + 1; } } } /*** Second part - Summary ***/ table.addCell(getPdfCell(String.valueOf(""), 0, 0, font)); table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(""), 0, 5, font)); table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT)); table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT)); if (!survey.getMessage().equals("")) { table.addCell(getPdfCell("", 0, 13, font)); table.addCell(getPdfCell("", 0, 0, font)); table.addCell(getPdfCell(survey.getMessage(), 0, 12, font, CENTER)); } table.setTotalWidth(750); table.setLockedWidth(true); table.setWidths(new float[] { 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }); ColumnText column = new ColumnText(pdfStamper.getOverContent(1)); Rectangle rectPage1 = new Rectangle(120, 20, 659, 480); column.setSimpleColumn(rectPage1); column.addElement(table); int status = column.go(); pdfStamper.setFormFlattening(true); pdfStamper.close(); pdfTemplate.close(); res.setContentType("application/pdf"); return res.getPortletOutputStream(); }
From source file:Operaciones.ResponsablesOP.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: h = new Herramientas(usr, 0); h.session(sessionPrograma);/* w w w .j av a 2 s . co m*/ Session session = HibernateUtil.getSessionFactory().openSession(); try { Orden ord = (Orden) session.get(Orden.class, Integer.parseInt(t_orden.getText())); Configuracion con = (Configuracion) session.get(Configuracion.class, 1); Date fecha = new Date(); Date fecha1 = new Date(); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS String valor = dateFormat.format(fecha); File folder = new File("reportes/" + ord.getIdOrden()); folder.mkdirs(); PdfReader reader = new PdfReader("imagenes/PlantillaHojaAsignacion.pdf"); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("reportes/" + ord.getIdOrden() + "/" + valor + "-HojaAsignacion.pdf")); PdfContentByte cb = stamp.getUnderContent(1); AcroFields fdfDoc = stamp.getAcroFields(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED); cb.beginText(); fdfDoc.setField("orden", String.valueOf(ord.getIdOrden())); if (ord.getCompania() != null) fdfDoc.setField("compania", ord.getCompania().getNombre()); else fdfDoc.setField("compania", ""); if (ord.getSiniestro() != null) fdfDoc.setField("siniestro", ord.getSiniestro()); else fdfDoc.setField("siniestro", ""); if (ord.getPoliza() != null) fdfDoc.setField("poliza", ord.getPoliza()); else fdfDoc.setField("poliza", ""); if (ord.getFecha() != null) fdfDoc.setField("apertura", ord.getFecha().toString()); else fdfDoc.setField("apertura", ""); if (ord.getFechaSiniestro() != null) fdfDoc.setField("f_siniestro", ord.getFechaSiniestro().toString()); else fdfDoc.setField("f_siniestro", ""); if (ord.getInciso() != null) fdfDoc.setField("inciso", ord.getInciso()); else fdfDoc.setField("inciso", ""); if (ord.getTipo() != null) fdfDoc.setField("unidad", ord.getTipo().getTipoNombre()); else fdfDoc.setField("unidad", ""); if (ord.getModelo() != null) fdfDoc.setField("modelo", ord.getModelo().toString()); else fdfDoc.setField("modelo", ""); if (ord.getMarca() != null) fdfDoc.setField("marca", ord.getMarca().getMarcaNombre()); else fdfDoc.setField("marca", ""); if (ord.getNoEconomico() != null) fdfDoc.setField("economico", ord.getNoEconomico()); else fdfDoc.setField("economico", ""); if (ord.getNoMotor() != null) fdfDoc.setField("no_motor", ord.getNoMotor()); else fdfDoc.setField("no_motor", ""); if (ord.getNoSerie() != null) fdfDoc.setField("no_serie", ord.getNoSerie()); else fdfDoc.setField("no_serie", ""); //tabla if (ord.getEmpleadoByRHojalateria() != null) fdfDoc.setField("HOJALATERIA", ord.getEmpleadoByRHojalateria().getIdEmpleado().toString()); else fdfDoc.setField("HOJALATERIA", ""); if (ord.getEmpleadoByRHojalateria() != null) fdfDoc.setField("R_H", ord.getEmpleadoByRHojalateria().getNombre().toString()); else fdfDoc.setField("R_H", ""); if (ord.getEmpleadoByRMecanica() != null) fdfDoc.setField("MECANICA", ord.getEmpleadoByRMecanica().getIdEmpleado().toString()); else fdfDoc.setField("MECANICA", ""); if (ord.getEmpleadoByRMecanica() != null) fdfDoc.setField("R_M", ord.getEmpleadoByRMecanica().getNombre().toString()); else fdfDoc.setField("R_M", ""); if (ord.getEmpleadoByRSuspension() != null) fdfDoc.setField("SUSPENSIN", ord.getEmpleadoByRSuspension().getIdEmpleado().toString()); else fdfDoc.setField("SUSPENSIN", ""); if (ord.getEmpleadoByRSuspension() != null) fdfDoc.setField("R_S", ord.getEmpleadoByRSuspension().getNombre().toString()); else fdfDoc.setField("R_S", ""); if (ord.getEmpleadoByRElectrico() != null) fdfDoc.setField("ELECTRICO", ord.getEmpleadoByRElectrico().getIdEmpleado().toString()); else fdfDoc.setField("ELECTRICO", ""); if (ord.getEmpleadoByRElectrico() != null) fdfDoc.setField("R_E", ord.getEmpleadoByRElectrico().getNombre().toString()); else fdfDoc.setField("R_E", ""); if (ord.getEmpleadoByRPintura() != null) fdfDoc.setField("PINTURA", ord.getEmpleadoByRPintura().getIdEmpleado().toString()); else fdfDoc.setField("PINTURA", ""); if (ord.getEmpleadoByRPintura() != null) fdfDoc.setField("R_P", ord.getEmpleadoByRPintura().getNombre().toString()); else fdfDoc.setField("R_P", ""); //FECHAS String valor1 = ""; if (ord.getRHojalateriaFecha() != null) { fecha1 = ord.getRHojalateriaFecha(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_H", valor1); } else { fdfDoc.setField("F_H", valor1); } if (ord.getRMecanicaFecha() != null) { fecha1 = ord.getRMecanicaFecha(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_M", valor1); } else { fdfDoc.setField("F_M", valor1); } if (ord.getRSuspensionFecha() != null) { fecha1 = ord.getRSuspensionFecha(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_S", valor1); } else { fdfDoc.setField("F_S", valor1); } if (ord.getRElectricoFecha() != null) { fecha1 = ord.getRElectricoFecha(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_E", valor1); } else { fdfDoc.setField("F_E", valor1); } if (ord.getRPinturaFecha() != null) { fecha1 = ord.getRPinturaFecha(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_P", valor1); } else { fdfDoc.setField("F_P", valor1); } //ASIGNO OPERARIO if (ord.getUsuarioByRHojalateriaAsigno() != null) fdfDoc.setField("A_H", ord.getUsuarioByRHojalateriaAsigno().getIdUsuario()); else fdfDoc.setField("A_H", ""); if (ord.getUsuarioByRMecanicaAsigno() != null) fdfDoc.setField("A_M", ord.getUsuarioByRMecanicaAsigno().getIdUsuario()); else fdfDoc.setField("A_M", ""); if (ord.getUsuarioByRSuspensionAsigno() != null) fdfDoc.setField("A_S", ord.getUsuarioByRSuspensionAsigno().getIdUsuario()); else fdfDoc.setField("A_S", ""); if (ord.getUsuarioByRElectricoAsigno() != null) fdfDoc.setField("A_E", ord.getUsuarioByRElectricoAsigno().getIdUsuario()); else fdfDoc.setField("A_E", ""); if (ord.getUsuarioByRPinturaAsigno() != null) fdfDoc.setField("A_P", ord.getUsuarioByRPinturaAsigno().getIdUsuario()); else fdfDoc.setField("A_P", ""); //LIMITE if (ord.getHojalateriaLimite() != null) { fecha1 = ord.getHojalateriaLimite(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_H_L", valor1); } else { fdfDoc.setField("F_H_L", ""); } if (ord.getMecanicaLimite() != null) { fecha1 = ord.getMecanicaLimite(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_M_L", valor1); } else { fdfDoc.setField("F_M_L", ""); } if (ord.getSuspensionLimite() != null) { fecha1 = ord.getSuspensionLimite(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_S_L", valor1); } else { fdfDoc.setField("F_S_L", ""); } if (ord.getElectricoLimite() != null) { fecha1 = ord.getElectricoLimite(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_E_L", valor1); } else { fdfDoc.setField("F_E_L", ""); } if (ord.getPinturaLimite() != null) { fecha1 = ord.getPinturaLimite(); dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); valor1 = dateFormat.format(fecha1); fdfDoc.setField("F_P_L", valor1); } else { fdfDoc.setField("F_P_L", ""); } Foto[] fotos = (Foto[]) ord.getFotos().toArray(new Foto[0]); for (int k = 0; k < fotos.length - 1; k++) { for (int f = 0; f < (fotos.length - 1) - k; f++) { if (fotos[f].getFecha().after(fotos[f + 1].getFecha()) == true) { Foto aux; aux = fotos[f]; fotos[f] = fotos[f + 1]; fotos[f + 1] = aux; } } } if (fotos.length > 0) { try { Image img; img = Image .getInstance("ordenes/" + ord.getIdOrden() + "/miniatura/" + fotos[0].getDescripcion()); img.setAbsolutePosition(30, 495); img.scaleAbsoluteWidth(124); img.scaleAbsoluteHeight(80); cb.addImage(img, true); } catch (Exception e) { //e.printStackTrace(); } } else { } cb.endText(); stamp.close(); PDF reporte = new PDF(); reporte.cerrar(); reporte.visualizar("reportes/" + ord.getIdOrden() + "/" + valor + "-HojaAsignacion.pdf"); } catch (Exception e) { System.out.println(e); JOptionPane.showMessageDialog(this, "No se pudo realizar el reporte si el archivo esta abierto"); } if (session != null) if (session.isOpen()) session.close(); }
From source file:org.alfresco.extension.countersign.action.executer.PDFAddSignatureFieldActionExecuter.java
License:Open Source License
/** * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef, * org.alfresco.service.cmr.repository.NodeRef) *///from w ww . java 2 s . c om protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) { NodeService ns = serviceRegistry.getNodeService(); if (ns.exists(actionedUponNodeRef) == false) { // node doesn't exist - can't do anything return; } String fieldName = (String) ruleAction.getParameterValue(PARAM_FIELDNAME); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); JSONObject box; int page = -1; // parse out the position JSON JSONObject positionObj = null; try { positionObj = (JSONObject) parser.parse(position); } catch (ParseException e) { logger.error("Could not parse position JSON from Share"); throw new AlfrescoRuntimeException("Could not parse position JSON from Share"); } // get the page page = Integer.parseInt(String.valueOf(positionObj.get("page"))); // get the box box = (JSONObject) positionObj.get("box"); try { // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); OutputStream cos = serviceRegistry.getContentService() .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream(); PdfStamper stamp = new PdfStamper(reader, cos); // does a field with this name already exist? AcroFields allFields = stamp.getAcroFields(); // if this doc is already signed, cannot add a new sig field without if (allFields.getSignatureNames() != null && allFields.getSignatureNames().size() > 0) { throw new AlfrescoRuntimeException("This document has signatures applied, " + "adding a new signature field would invalidate existing signatures"); } // cant create duplicate field names if (allFields.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) { throw new AlfrescoRuntimeException( "A signature field named " + fieldName + " already exists in this document"); } // create the signature field Rectangle pageRect = reader.getPageSizeWithRotation(page); Rectangle sigRect = positionBlock(pageRect, box); PdfFormField sigField = stamp.addSignature(fieldName, page, sigRect.getLeft(), sigRect.getBottom(), sigRect.getRight(), sigRect.getTop()); // style the field (no borders) sigField.setBorder(new PdfBorderArray(0, 0, 0)); sigField.setBorderStyle(new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID)); allFields.regenerateField(fieldName); // apply the change and close streams stamp.close(); reader.close(); cos.close(); // once the signature field has been added, apply the sig field aspect if (!ns.hasAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE)) { ns.addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE, null); } // now update the signature fields metadata Serializable currentFields = ns.getProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS); ArrayList<String> fields = new ArrayList<String>(); if (currentFields != null) { fields.addAll((List<String>) currentFields); } fields.add(fieldName); ns.setProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, fields); } catch (IOException ioex) { throw new AlfrescoRuntimeException(ioex.getMessage()); } catch (DocumentException dex) { throw new AlfrescoRuntimeException(dex.getMessage()); } }
From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java
License:Open Source License
/** * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef, * org.alfresco.service.cmr.repository.NodeRef) *//*from w w w . j a v a 2 s. c o m*/ protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) { // node doesn't exist - can't do anything return; } String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON); Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE); Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC); boolean useSignatureField = false; String user = AuthenticationUtil.getRunAsUser(); String positionType = "predefined"; String positionLoc = "center"; JSONObject box; int page = -1; // parse out the position JSON JSONObject positionObj = null; try { positionObj = (JSONObject) parser.parse(position); } catch (ParseException e) { logger.error("Could not parse position JSON from Share"); throw new AlfrescoRuntimeException("Could not parse position JSON from Share"); } // get the page page = Integer.parseInt(String.valueOf(positionObj.get("page"))); // get the positioning type positionType = String.valueOf(positionObj.get("type")); // get the position (field or predefined) positionLoc = String.valueOf(positionObj.get("position")); // get the box (if required) box = (JSONObject) positionObj.get("box"); int width = 350; int height = 75; File tempDir = null; // current date, used for both signing the PDF and creating the // associated signature object Calendar now = Calendar.getInstance(); try { // get the keystore, pk and cert chain SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user); KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword); PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = keystore.getCertificateChain(alias); // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); // create temp dir to store file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); OutputStream cos = serviceRegistry.getContentService() .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream(); PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); // set reason for signature, location of signer, and date sap.setReason(reason); sap.setLocation(location); sap.setSignDate(now); // get the image for the signature BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height); // save the signature image back to the signatureProvider signatureProvider.saveSignatureImage(sigImage, signatureJson); if (visible) { //if this is a graphic sig, set the graphic here if (graphic) { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE)); } else { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); } // either insert the sig at a defined field or at a defined position / drawn loc if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null); } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(pageRect, box), page, null); } else { sap.setVisibleSignature(positionLoc); useSignatureField = true; } } // close the stamp, applying the changes to the PDF stamp.close(); reader.close(); cos.close(); //delete the temp file file.delete(); // apply the "signed" aspect serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); // create a "signature" node and associate it with the signed doc addSignatureNodeAssociation(actionedUponNodeRef, location, reason, useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFEncryptionActionExecuter.java
License:Apache License
/** * @param reader/* w w w . ja v a2 s . c o m*/ * @param writer * @param options * @throws Exception */ protected final void action(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; try { // get the parameters String userPassword = (String) options.get(PARAM_USER_PASSWORD); String ownerPassword = (String) options.get(PARAM_OWNER_PASSWORD); int permissions = buildPermissionMask(options); int encryptionType = Integer.parseInt((String) options.get(PARAM_ENCRYPTION_LEVEL)); // if metadata is excluded, alter encryption type if ((Boolean) options.get(PARAM_EXCLUDE_METADATA)) { encryptionType = encryptionType | PdfWriter.DO_NOT_ENCRYPT_METADATA; } // get temp file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); // get the PDF input stream and create a reader for iText PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); // encrypt PDF stamp.setEncryption(userPassword.getBytes(Charset.forName("UTF-8")), ownerPassword.getBytes(Charset.forName("UTF-8")), permissions, encryptionType); stamp.close(); // write out to destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); writer.putContent(file); file.delete(); //if useAspect is true, store some additional info about the signature in the props if (useAspect) { serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_ENCRYPTED, new HashMap<QName, Serializable>()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_ENCRYPTIONDATE, new java.util.Date()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_ENCRYPTEDBY, AuthenticationUtil.getRunAsUser()); } } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }