List of usage examples for com.itextpdf.text.pdf PdfStamper PdfStamper
public PdfStamper(final PdfReader reader, final OutputStream os) throws DocumentException, IOException
From source file:om.edu.squ.squportal.portlet.tsurvey.dao.pdf.TeachingSurveyPdfImpl.java
License:Open Source License
/** * // ww w . j a v a2s . c om * 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);/*from w w w. ja va 2 s . com*/ 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) */// www . j a v a 2 s . c o m 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.pdftoolkit.repo.action.executer.PDFEncryptionActionExecuter.java
License:Apache License
/** * @param reader// ww w . jav a 2 s. co 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); } } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
License:Apache License
/** * Applies an image watermark// w ww . ja v a 2 s . c o m * * @param reader * @param writer * @param options * @throws Exception */ private void imageAction(Action ruleAction, NodeRef actionedUponNodeRef, NodeRef watermarkNodeRef, ContentReader actionedUponContentReader, ContentReader watermarkContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; try { // get a temp file to stash the watermarked PDF in before moving to // repo 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)); PdfContentByte pcb; // get a com.itextpdf.text.Image object via java.imageio.ImageIO Image img = Image.getInstance(ImageIO.read(watermarkContentReader.getContentInputStream()), null); // get the PDF pages and position String pages = (String) options.get(PARAM_PAGE); String position = (String) options.get(PARAM_POSITION); String depth = (String) options.get(PARAM_WATERMARK_DEPTH); // image requires absolute positioning or an exception will be // thrown // set image position according to parameter. Use // PdfReader.getPageSizeWithRotation // to get the canvas size for alignment. img.setAbsolutePosition(100f, 100f); // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // set stamp position if (position.equals(POSITION_BOTTOMLEFT)) { img.setAbsolutePosition(0, 0); } else if (position.equals(POSITION_BOTTOMRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), 0); } else if (position.equals(POSITION_TOPLEFT)) { img.setAbsolutePosition(0, r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_TOPRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_CENTER)) { img.setAbsolutePosition(getCenterX(r, img), getCenterY(r, img)); } // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, usse getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { pcb.addImage(img); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the 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); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } 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); } } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
License:Apache License
/** * Applies a text watermark (current date, user name, etc, depending on * options)/* ww w. jav a2s.co m*/ * * @param reader * @param writer * @param options */ private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; String watermarkText; StringTokenizer st; Vector<String> tokens = new Vector<String>(); try { // get a temp file to stash the watermarked PDF in before moving to // repo 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)); PdfContentByte pcb; // get the PDF pages and position String pages = (String) options.get(PARAM_PAGE); String position = (String) options.get(PARAM_POSITION); String depth = (String) options.get(PARAM_WATERMARK_DEPTH); // create the base font for the text stamp BaseFont bf = BaseFont.createFont((String) options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250, BaseFont.EMBEDDED); // get watermark text and process template with model String templateText = (String) options.get(PARAM_WATERMARK_TEXT); Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef); StringWriter watermarkWriter = new StringWriter(); freemarkerProcessor.processString(templateText, model, watermarkWriter); watermarkText = watermarkWriter.getBuffer().toString(); // tokenize watermark text to support multiple lines and copy tokens // to vector for re-use st = new StringTokenizer(watermarkText, "\r\n", false); while (st.hasMoreTokens()) { tokens.add(st.nextToken()); } // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, use getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // set the font and size float size = Float.parseFloat((String) options.get(PARAM_WATERMARK_SIZE)); pcb.setFontAndSize(bf, size); // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { writeAlignedText(pcb, r, tokens, size, position); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the 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); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } 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); } } } }
From source file:org.cejug.footprint.FootPrint.java
License:Open Source License
public byte[] generate() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/*w w w . j a va 2 s . c om*/ PdfStamper stamper = new PdfStamper(reader, baos); AcroFields fields = stamper.getAcroFields(); Set<String> keys = fields.getFields().keySet(); for (String k : keys) { fields.setField(k, values.get(k)); } stamper.close(); } catch (DocumentException | IOException e) { e.printStackTrace(); } return baos.toByteArray(); }
From source file:org.crossref.pdfmark.Main.java
License:Open Source License
public Main(String[] args) { if (args.length == 0) { printUsage();/*from w w w. j a v a2s .c o m*/ System.exit(2); } CmdLineParser parser = new CmdLineParser(); Option provideXmpOp = parser.addStringOption('p', "xmp-file"); Option overwriteOp = parser.addBooleanOption('f', "force"); Option outputOp = parser.addStringOption('o', "output-dir"); Option doiOp = parser.addStringOption('d', "doi"); Option searchOp = parser.addBooleanOption('s', "search-for-doi"); Option copyrightOp = parser.addBooleanOption("no-copyright"); Option rightsOp = parser.addStringOption("rights-agent"); Option apiKeyOp = parser.addStringOption("api-key"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { printUsage(); System.exit(2); } String optionalXmpPath = (String) parser.getOptionValue(provideXmpOp, ""); String outputDir = (String) parser.getOptionValue(outputOp, ""); String explicitDoi = (String) parser.getOptionValue(doiOp, ""); boolean useTheForce = (Boolean) parser.getOptionValue(overwriteOp, Boolean.FALSE); boolean searchForDoi = (Boolean) parser.getOptionValue(searchOp, Boolean.FALSE); boolean noCopyright = (Boolean) parser.getOptionValue(copyrightOp, Boolean.FALSE); String rightsAgent = (String) parser.getOptionValue(rightsOp, ""); String apiKey = (String) parser.getOptionValue(apiKeyOp, ApiKey.DEFAULT); if (!explicitDoi.equals("") && searchForDoi) { exitWithError(2, "-d and -s are mutually exclusive options."); } if (!outputDir.isEmpty() && !new File(outputDir).exists()) { exitWithError(2, "The output directory, '" + outputDir + "' does not exist."); } byte[] optionalXmpData = null; if (!optionalXmpPath.equals("")) { /* We will take XMP data from a file. */ FileInfo xmpFile = FileInfo.readFileFully(optionalXmpPath); if (xmpFile.missing) { exitWithError(2, "Error: File '" + xmpFile.path + "' does not exist."); } else if (xmpFile.error != null) { exitWithError(2, "Error: Could not read '" + xmpFile.path + "' because of:\n" + xmpFile.error); } optionalXmpData = xmpFile.data; } grabber = new MetadataGrabber(apiKey); /* Now we're ready to merge our imported or generated XMP data with what * is already in each PDF. */ for (String pdfFilePath : parser.getRemainingArgs()) { String outputPath = getOutFileName(pdfFilePath); /* Grab the leaf. */ if (outputPath.contains(File.separator)) { String[] split = outputPath.split(File.separator); outputPath = split[split.length - 1]; } if (!outputDir.isEmpty()) { outputPath = outputDir + File.separator + outputPath; } else { /* Output to the working directory. */ } File pdfFile = new File(pdfFilePath); File outputFile = new File(outputPath); byte[] resolvedXmpData = null; if (!pdfFile.exists()) { exitWithError(2, "Error: File '" + pdfFilePath + "' does not exist."); } if (outputFile.exists() && !useTheForce) { exitWithError(2, "Error: File '" + outputPath + "' already exists.\nTry using -f (force)."); } try { if (!useTheForce && isLinearizedPdf(new FileInputStream(pdfFile))) { exitWithError(2, "Error: '" + pdfFilePath + "' is a" + " linearized PDF and force is not specified." + " This tool will output non-linearized PDF." + "\nIf you don't mind that, use -f (force)."); } } catch (IOException e) { exitWithError(2, "Error: Could not determine linearization" + " because of:\n" + e); } if (!explicitDoi.equals("")) { resolvedXmpData = getXmpForDoi(explicitDoi, !noCopyright, rightsAgent); } try { new File(outputFile.getPath() + ".tmp").deleteOnExit(); FileInputStream fileIn = new FileInputStream(pdfFile); FileOutputStream fileOut = new FileOutputStream(outputFile.getPath() + ".tmp"); PdfReader reader = new PdfReader(fileIn); PdfStamper stamper = new PdfStamper(reader, fileOut); byte[] merged = reader.getMetadata(); if (optionalXmpData != null) { merged = XmpUtils.mergeXmp(merged, optionalXmpData); } if (resolvedXmpData != null) { merged = XmpUtils.mergeXmp(merged, resolvedXmpData); } stamper.setXmpMetadata(merged); stamper.close(); reader.close(); fileIn = new FileInputStream(outputFile.getPath() + ".tmp"); writeInfoDictionary(fileIn, outputFile.getPath(), merged); } catch (IOException e) { exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e); } catch (DocumentException e) { exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e); } catch (XmpException e) { exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e); } catch (COSVisitorException e) { exitWithError(2, "Error: Couldn't write document info dictionary" + " because of:\n" + e); } } shutDown(); }
From source file:org.freemedsoftware.util.CompositePdfForm.java
License:Open Source License
public static void main(String[] args) throws Exception { CommandLineParser parser = new GnuParser(); CommandLine line = null;//w w w.j a v a 2 s . co m try { line = parser.parse(getOptions(), args); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } String dataFile = line.getOptionValue("i"); String templateFile = line.getOptionValue("t"); String outputFile = line.getOptionValue("o"); if (dataFile == null || templateFile == null || outputFile == null) { System.err.println("options:"); System.err.println("\t[-i|--input] Input file name"); System.err.println("\t[-t|--template] PDF template"); System.err.println("\t[-o|--output] Output file name"); System.exit(1); } if (!(new File(dataFile).exists())) { System.err.println("Could not open input data file " + dataFile); System.exit(1); } if (!(new File(templateFile).exists())) { System.err.println("Could not open template file " + templateFile); System.exit(1); } Serializer serializer = new Persister(); FormElementList elementList = serializer.read(FormElementList.class, new File(dataFile)); PdfReader templateReader = new PdfReader(templateFile); PdfStamper stamper = new PdfStamper(templateReader, new FileOutputStream(outputFile)); // Iterate fillForm(stamper.getAcroFields(), elementList); stamper.close(); System.exit(0); }
From source file:org.h819.commons.file.MyPDFUtils.java
/** * pdf ? pdf/*w w w.j ava 2 s . co m*/ * * @param srcPdf the original PDF * @param destPdf the resulting PDF * @param imageFactor The multiplication factor for the image (? imageFacto =0.5f) * @throws IOException * @throws DocumentException */ public static void compressPdf(File srcPdf, File destPdf, float imageFactor) throws IOException, DocumentException { PdfReader reader = new PdfReader(srcPdf.getAbsolutePath()); int n = reader.getXrefSize(); PdfObject object; PRStream stream; // Look for image and manipulate image stream for (int i = 0; i < n; i++) { object = reader.getPdfObject(i); if (object == null || !object.isStream()) continue; stream = (PRStream) object; if (!PdfName.IMAGE.equals(stream.getAsName(PdfName.SUBTYPE))) continue; if (!PdfName.DCTDECODE.equals(stream.getAsName(PdfName.FILTER))) continue; PdfImageObject image = new PdfImageObject(stream); BufferedImage bi = image.getBufferedImage(); if (bi == null) continue; int width = (int) (bi.getWidth() * imageFactor); int height = (int) (bi.getHeight() * imageFactor); if (width <= 0 || height <= 0) continue; BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); AffineTransform at = AffineTransform.getScaleInstance(imageFactor, imageFactor); Graphics2D g = img.createGraphics(); g.drawRenderedImage(bi, at); ByteArrayOutputStream imgBytes = new ByteArrayOutputStream(); ImageIO.write(img, "JPG", imgBytes); stream.clear(); stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION); stream.put(PdfName.TYPE, PdfName.XOBJECT); stream.put(PdfName.SUBTYPE, PdfName.IMAGE); stream.put(PdfName.FILTER, PdfName.DCTDECODE); stream.put(PdfName.WIDTH, new PdfNumber(width)); stream.put(PdfName.HEIGHT, new PdfNumber(height)); stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8)); stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB); } reader.removeUnusedObjects(); // Save altered PDF PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPdf.getAbsolutePath())); stamper.setFullCompression(); stamper.close(); reader.close(); }