List of usage examples for com.lowagie.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java
License:Open Source License
@Override public Blob signPDF(Blob pdfBlob, DocumentModel user, String keyPassword, String reason) throws ClientException { CertService certService = Framework.getLocalService(CertService.class); CUserService cUserService = Framework.getLocalService(CUserService.class); try {/*from w w w . ja v a2s . c om*/ File outputFile = File.createTempFile("signed-", ".pdf"); Blob blob = Blobs.createBlob(outputFile, MIME_TYPE_PDF); Framework.trackFile(outputFile, blob); PdfReader pdfReader = new PdfReader(pdfBlob.getStream()); List<X509Certificate> pdfCertificates = getCertificates(pdfReader); // allows for multiple signatures PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, new FileOutputStream(outputFile), '\0', null, true); PdfSignatureAppearance pdfSignatureAppearance = pdfStamper.getSignatureAppearance(); String userID = (String) user.getPropertyValue("user:username"); AliasWrapper alias = new AliasWrapper(userID); KeyStore keystore = cUserService.getUserKeystore(userID, keyPassword); Certificate certificate = certService.getCertificate(keystore, alias.getId(AliasType.CERT)); KeyPair keyPair = certService.getKeyPair(keystore, alias.getId(AliasType.KEY), alias.getId(AliasType.CERT), keyPassword); if (certificatePresentInPDF(certificate, pdfCertificates)) { X509Certificate userX509Certificate = (X509Certificate) certificate; String message = ALREADY_SIGNED_BY + userX509Certificate.getSubjectDN(); log.debug(message); throw new AlreadySignedException(message); } List<Certificate> certificates = new ArrayList<Certificate>(); certificates.add(certificate); Certificate[] certChain = certificates.toArray(new Certificate[0]); pdfSignatureAppearance.setCrypto(keyPair.getPrivate(), certChain, null, PdfSignatureAppearance.SELF_SIGNED); if (StringUtils.isBlank(reason)) { reason = getSigningReason(); } pdfSignatureAppearance.setReason(reason); pdfSignatureAppearance.setAcro6Layers(true); Font layer2Font = FontFactory.getFont(FontFactory.TIMES, getSignatureLayout().getTextSize(), Font.NORMAL, new Color(0x00, 0x00, 0x00)); pdfSignatureAppearance.setLayer2Font(layer2Font); pdfSignatureAppearance.setRender(PdfSignatureAppearance.SignatureRenderDescription); pdfSignatureAppearance.setVisibleSignature(getNextCertificatePosition(pdfReader, pdfCertificates), 1, null); pdfStamper.close(); // closes the file log.debug("File " + outputFile.getAbsolutePath() + " created and signed with " + reason); return blob; } catch (IOException e) { throw new SignException(e); } catch (DocumentException e) { // iText PDF stamping throw new SignException(e); } catch (IllegalArgumentException e) { if (String.valueOf(e.getMessage()).contains("PdfReader not opened with owner password")) { // iText PDF reading throw new SignException("PDF is password-protected"); } throw new SignException(e); } }
From source file:org.obiba.onyx.print.impl.DefaultPdfTemplateEngine.java
License:Open Source License
public InputStream applyTemplate(Locale locale, Map<String, String> fieldToVariableMap, LocalizedResourceLoader reportTemplateLoader, ActiveInterviewService activeInterviewService) { // Get report template Resource resource = reportTemplateLoader.getLocalizedResource(locale); // Read report template PdfReader pdfReader;/* www . j a v a 2 s. c o m*/ try { pdfReader = new PdfReader(resource.getInputStream()); } catch (Exception ex) { throw new RuntimeException("Report to participant template cannot be read", ex); } ByteArrayOutputStream output = new ByteArrayOutputStream(); PdfStamper stamper = null; // Set the values in the report data fields try { stamper = new PdfStamper(pdfReader, output); stamper.setFormFlattening(true); AcroFields form = stamper.getAcroFields(); Participant participant = activeInterviewService.getParticipant(); setVariableDataFields(participant, form, fieldToVariableMap, locale); setAdditionalDataFields(form); } catch (Exception ex) { throw new RuntimeException("An error occured while preparing the report to participant", ex); } finally { try { stamper.close(); } catch (Exception e) { log.warn("Could not close PdfStamper", e); } try { output.close(); } catch (IOException e) { log.warn("Could not close OutputStream", e); } pdfReader.close(); } return new ByteArrayInputStream(output.toByteArray()); }
From source file:org.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * *//*from w ww. ja v a 2s . co m*/ public static Map<String, Object> buildSurveyFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); Timestamp nowTimestamp = UtilDateTime.nowTimestamp(); String surveyId = null; try { String surveyName = (String) context.get("surveyName"); ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteBuffer byteBuffer = getInputByteBuffer(context, delegator); PdfReader pdfReader = new PdfReader(byteBuffer.array()); PdfStamper pdfStamper = new PdfStamper(pdfReader, os); AcroFields acroFields = pdfStamper.getAcroFields(); Map<String, Object> acroFieldMap = UtilGenerics.checkMap(acroFields.getFields()); String contentId = (String) context.get("contentId"); GenericValue survey = null; surveyId = (String) context.get("surveyId"); if (UtilValidate.isEmpty(surveyId)) { survey = delegator.makeValue("Survey", UtilMisc.toMap("surveyName", surveyName)); survey.set("surveyId", surveyId); survey.set("allowMultiple", "Y"); survey.set("allowUpdate", "Y"); survey = delegator.createSetNextSeqId(survey); surveyId = survey.getString("surveyId"); } // create a SurveyQuestionCategory to put the questions in Map<String, Object> createCategoryResultMap = dispatcher.runSync("createSurveyQuestionCategory", UtilMisc.<String, Object>toMap("description", "From AcroForm in Content [" + contentId + "] for Survey [" + surveyId + "]", "userLogin", userLogin)); String surveyQuestionCategoryId = (String) createCategoryResultMap.get("surveyQuestionCategoryId"); pdfStamper.setFormFlattening(true); for (String fieldName : acroFieldMap.keySet()) { AcroFields.Item item = acroFields.getFieldItem(fieldName); int type = acroFields.getFieldType(fieldName); String value = acroFields.getField(fieldName); Debug.logInfo("fieldName:" + fieldName + "; item: " + item + "; value: " + value, module); GenericValue surveyQuestion = delegator.makeValue("SurveyQuestion", UtilMisc.toMap("question", fieldName)); String surveyQuestionId = delegator.getNextSeqId("SurveyQuestion"); surveyQuestion.set("surveyQuestionId", surveyQuestionId); surveyQuestion.set("surveyQuestionCategoryId", surveyQuestionCategoryId); if (type == AcroFields.FIELD_TYPE_TEXT) { surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT"); } else if (type == AcroFields.FIELD_TYPE_RADIOBUTTON) { surveyQuestion.set("surveyQuestionTypeId", "OPTION"); } else if (type == AcroFields.FIELD_TYPE_LIST || type == AcroFields.FIELD_TYPE_COMBO) { surveyQuestion.set("surveyQuestionTypeId", "OPTION"); // TODO: handle these specially with the acroFields.getListOptionDisplay (and getListOptionExport?) /*String[] listOptionDisplayArray = acroFields.getListOptionDisplay(fieldName); String[] listOptionExportArray = acroFields.getListOptionExport(fieldName); Debug.logInfo("listOptionDisplayArray: " + listOptionDisplayArray + "; listOptionExportArray: " + listOptionExportArray, module);*/ } else { surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT"); Debug.logWarning("Building Survey from PDF, fieldName=[" + fieldName + "]: don't know how to handle field type: " + type + "; defaulting to short text", module); } // ==== create a good sequenceNum based on tab order or if no tab order then the page location Integer tabPage = item.getPage(0); Integer tabOrder = item.getTabOrder(0); Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder, module); //array of float multiple of 5. For each of this groups the values are: [page, llx, lly, urx, ury] float[] fieldPositions = acroFields.getFieldPositions(fieldName); float fieldPage = fieldPositions[0]; float fieldLlx = fieldPositions[1]; float fieldLly = fieldPositions[2]; float fieldUrx = fieldPositions[3]; float fieldUry = fieldPositions[4]; Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry, module); Long sequenceNum = null; if (tabPage != null && tabOrder != null) { sequenceNum = Long.valueOf(tabPage.intValue() * 1000 + tabOrder.intValue()); Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder + ", sequenceNum=" + sequenceNum, module); } else if (fieldPositions.length > 0) { sequenceNum = Long.valueOf((long) fieldPage * 10000 + (long) fieldLly * 1000 + (long) fieldLlx); Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry + ", sequenceNum=" + sequenceNum, module); } // TODO: need to find something better to put into these fields... String annotation = null; for (int k = 0; k < item.size(); ++k) { PdfDictionary dict = item.getWidget(k); // if the "/Type" value is "/Annot", then get the value of "/TU" for the annotation /* Interesting... this doesn't work, I guess we have to iterate to find the stuff... PdfObject typeValue = dict.get(new PdfName("/Type")); if (typeValue != null && "/Annot".equals(typeValue.toString())) { PdfObject tuValue = dict.get(new PdfName("/TU")); annotation = tuValue.toString(); } */ PdfObject typeValue = null; PdfObject tuValue = null; Set<PdfName> dictKeys = UtilGenerics.checkSet(dict.getKeys()); for (PdfName dictKeyName : dictKeys) { PdfObject dictObject = dict.get(dictKeyName); if ("/Type".equals(dictKeyName.toString())) { typeValue = dictObject; } else if ("/TU".equals(dictKeyName.toString())) { tuValue = dictObject; } //Debug.logInfo("AcroForm widget fieldName[" + fieldName + "] dictKey[" + dictKeyName.toString() + "] dictValue[" + dictObject.toString() + "]", module); } if (tuValue != null && typeValue != null && "/Annot".equals(typeValue.toString())) { annotation = tuValue.toString(); } } surveyQuestion.set("description", fieldName); if (UtilValidate.isNotEmpty(annotation)) { surveyQuestion.set("question", annotation); } else { surveyQuestion.set("question", fieldName); } GenericValue surveyQuestionAppl = delegator.makeValue("SurveyQuestionAppl", UtilMisc.toMap("surveyId", surveyId, "surveyQuestionId", surveyQuestionId)); surveyQuestionAppl.set("fromDate", nowTimestamp); surveyQuestionAppl.set("externalFieldRef", fieldName); if (sequenceNum != null) { surveyQuestionAppl.set("sequenceNum", sequenceNum); } surveyQuestion.create(); surveyQuestionAppl.create(); } pdfStamper.close(); if (UtilValidate.isNotEmpty(contentId)) { survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne(); survey.set("acroFormContentId", contentId); survey.store(); } } catch (GenericEntityException e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale)); } catch (GeneralException e) { Debug.logError(e, "Error generating PDF: " + e.getMessage(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.getMessage()), locale)); } catch (Exception e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale)); } Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("surveyId", surveyId); return results; }
From source file:org.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** * *//*from ww w . ja va2 s . co m*/ public static Map<String, Object> buildSurveyResponseFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) { String surveyResponseId = null; Locale locale = (Locale) context.get("locale"); try { Delegator delegator = dctx.getDelegator(); String partyId = (String) context.get("partyId"); String surveyId = (String) context.get("surveyId"); //String contentId = (String)context.get("contentId"); surveyResponseId = (String) context.get("surveyResponseId"); if (UtilValidate.isNotEmpty(surveyResponseId)) { GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse") .where("surveyResponseId", surveyResponseId).queryOne(); if (surveyResponse != null) { surveyId = surveyResponse.getString("surveyId"); } } else { surveyResponseId = delegator.getNextSeqId("SurveyResponse"); GenericValue surveyResponse = delegator.makeValue("SurveyResponse", UtilMisc .toMap("surveyResponseId", surveyResponseId, "surveyId", surveyId, "partyId", partyId)); surveyResponse.set("responseDate", UtilDateTime.nowTimestamp()); surveyResponse.set("lastModifiedDate", UtilDateTime.nowTimestamp()); surveyResponse.create(); } ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteBuffer byteBuffer = getInputByteBuffer(context, delegator); PdfReader r = new PdfReader(byteBuffer.array()); PdfStamper s = new PdfStamper(r, os); AcroFields fs = s.getAcroFields(); Map<String, Object> hm = UtilGenerics.checkMap(fs.getFields()); s.setFormFlattening(true); for (String fieldName : hm.keySet()) { //AcroFields.Item item = fs.getFieldItem(fieldName); //int type = fs.getFieldType(fieldName); String value = fs.getField(fieldName); GenericValue surveyQuestionAndAppl = EntityQuery.use(delegator).from("SurveyQuestionAndAppl") .where("surveyId", surveyId, "externalFieldRef", fieldName).queryFirst(); if (surveyQuestionAndAppl == null) { Debug.logInfo( "No question found for surveyId:" + surveyId + " and externalFieldRef:" + fieldName, module); continue; } String surveyQuestionId = (String) surveyQuestionAndAppl.get("surveyQuestionId"); String surveyQuestionTypeId = (String) surveyQuestionAndAppl.get("surveyQuestionTypeId"); GenericValue surveyResponseAnswer = delegator.makeValue("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyQuestionId", surveyQuestionId)); if (surveyQuestionTypeId == null || surveyQuestionTypeId.equals("TEXT_SHORT")) { surveyResponseAnswer.set("textResponse", value); } delegator.create(surveyResponseAnswer); } s.close(); } catch (GenericEntityException e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale)); } catch (GeneralException e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.getMessage()), locale)); } catch (Exception e) { Debug.logError(e, "Error generating PDF: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale)); } Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("surveyResponseId", surveyResponseId); return results; }
From source file:org.ofbiz.content.survey.PdfSurveyServices.java
License:Apache License
/** */// w w w. j a v a 2s .co m public static Map<String, Object> setAcroFields(DispatchContext dctx, Map<String, ? extends Object> context) { Map<String, Object> results = ServiceUtil.returnSuccess(); Delegator delegator = dctx.getDelegator(); try { Map<String, Object> acroFieldMap = UtilGenerics.checkMap(context.get("acroFieldMap")); ByteBuffer byteBuffer = getInputByteBuffer(context, delegator); PdfReader r = new PdfReader(byteBuffer.array()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfStamper s = new PdfStamper(r, baos); AcroFields fs = s.getAcroFields(); Map<String, Object> map = UtilGenerics.checkMap(fs.getFields()); s.setFormFlattening(true); // Debug code to get the values for setting TDP // String[] sa = fs.getAppearanceStates("TDP"); // for (int i=0;i<sa.length;i++) // Debug.logInfo("Appearance="+sa[i]); for (String fieldName : map.keySet()) { String fieldValue = fs.getField(fieldName); Object obj = acroFieldMap.get(fieldName); if (obj instanceof Date) { Date d = (Date) obj; fieldValue = UtilDateTime.toDateString(d); } else if (obj instanceof Long) { Long lg = (Long) obj; fieldValue = lg.toString(); } else if (obj instanceof Integer) { Integer ii = (Integer) obj; fieldValue = ii.toString(); } else { fieldValue = (String) obj; } if (UtilValidate.isNotEmpty(fieldValue)) { fs.setField(fieldName, fieldValue); } } s.close(); baos.close(); ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray()); results.put("outByteBuffer", outByteBuffer); } catch (DocumentException e) { System.err.println(e.getMessage()); results = ServiceUtil.returnError(e.getMessage()); } catch (GeneralException e) { System.err.println(e.getMessage()); results = ServiceUtil.returnError(e.getMessage()); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); results = ServiceUtil.returnError(e.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); results = ServiceUtil.returnError(ioe.getMessage()); } catch (Exception ioe) { System.err.println(ioe.getMessage()); results = ServiceUtil.returnError(ioe.getMessage()); } return results; }
From source file:org.openconcerto.erp.core.finance.accounting.report.PDFImageInsertor.java
License:Open Source License
public void insert(File pdf, Image img, int page, boolean under) throws Exception { PdfReader reader;// w w w . j a v a 2s .c o m reader = new PdfReader(new FileInputStream(pdf)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdf)); // img.setAbsolutePosition(20, 40); // int total = reader.getNumberOfPages() + 1; PdfContentByte content; if (under) { content = stamper.getUnderContent(page); } else { content = stamper.getOverContent(page); } content.addImage(img); stamper.close(); }
From source file:org.openelis.bean.WorksheetPrintReportBean.java
License:Open Source License
private Path fillPDFWorksheet(Integer worksheetId, String templateName, String userName) throws Exception { int i, j, formCapacity, diagramCapacity, pageNumber; AcroFields form;//from w ww . ja v a 2 s . c o m AnalysisViewDO aVDO; ArrayList<AnalysisQaEventViewDO> aqeVDOs; ArrayList<Integer> analysisIds, qcLotIds; ArrayList<NoteViewDO> nVDOs; ArrayList<QcAnalyteViewDO> qaVDOs; ArrayList<QcLotViewDO> qlVDOs; ArrayList<SampleManager1> sMans; ArrayList<SampleOrganizationViewDO> sOrgs; ArrayList<SampleQaEventViewDO> sqeVDOs; ArrayList<SystemVariableDO> sysVars; ArrayList<WorksheetAnalysisViewDO> waVDOs; ByteArrayOutputStream page; Document doc; HashMap<Integer, ArrayList<QcAnalyteViewDO>> qaVDOMap; HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>> waVDOMap; HashMap<Integer, QcLotViewDO> qlMap; HashMap<Integer, SampleManager1> sMap; OutputStream out; Path path; PatientDO patDO; PdfCopy writer; PdfReader reader; PdfStamper stamper; ProviderDO proDO; QcLotViewDO qlVDO; RandomAccessFileOrArray original; SampleEnvironmentalDO seDO; SampleDO sDO; SampleItemViewDO siVDO; SampleManager1 sMan; String collectionDateTime, dirName, now, qcLink; StringBuilder aNotes, aQaevents, sNotes, sQaevents; WorksheetAnalysisDO waDO1; WorksheetItemDO wiDO1; WorksheetManager1 wMan; WorksheetViewDO wVDO; now = ReportUtil.toString(new Date(), Messages.get().dateTimePattern()); dirName = ""; try { sysVars = systemVariable.fetchByName("worksheet_template_directory", 1); if (sysVars.size() > 0) dirName = ((SystemVariableDO) sysVars.get(0)).getValue(); } catch (Exception anyE) { throw new Exception("Error retrieving temp directory variable: " + anyE.getMessage()); } analysisIds = new ArrayList<Integer>(); qcLotIds = new ArrayList<Integer>(); waVDOMap = new HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>>(); wMan = worksheetManager.fetchById(worksheetId, WorksheetManager1.Load.DETAIL, WorksheetManager1.Load.REAGENT); for (WorksheetAnalysisViewDO data : WorksheetManager1Accessor.getAnalyses(wMan)) { waVDOs = waVDOMap.get(data.getWorksheetItemId()); if (waVDOs == null) { waVDOs = new ArrayList<WorksheetAnalysisViewDO>(); waVDOMap.put(data.getWorksheetItemId(), waVDOs); } waVDOs.add(data); if (data.getAnalysisId() != null) analysisIds.add(data.getAnalysisId()); else if (data.getQcLotId() != null) qcLotIds.add(data.getQcLotId()); } sMap = new HashMap<Integer, SampleManager1>(); if (analysisIds.size() > 0) { sMans = sampleManager.fetchByAnalyses(analysisIds, SampleManager1.Load.ORGANIZATION, SampleManager1.Load.QA, SampleManager1.Load.NOTE, SampleManager1.Load.SINGLEANALYSIS, SampleManager1.Load.PROVIDER); for (SampleManager1 data : sMans) { for (AnalysisViewDO data1 : SampleManager1Accessor.getAnalyses(data)) sMap.put(data1.getId(), data); } } qaVDOMap = new HashMap<Integer, ArrayList<QcAnalyteViewDO>>(); qlMap = new HashMap<Integer, QcLotViewDO>(); if (qcLotIds.size() > 0) { qlVDOs = qcLot.fetchByIds(qcLotIds); for (QcLotViewDO data : qlVDOs) { qlMap.put(data.getId(), data); try { qaVDOs = qcAnalyte.fetchByQcId(data.getQcId()); qaVDOMap.put(data.getQcId(), qaVDOs); } catch (NotFoundException nfE) { // ignore this error as leaving the hash record blank will not // cause an error due to a null check later on in the code } } } formCapacity = 1; out = null; try { path = ReportUtil.createTempFile("worksheetPrint", ".pdf", null); out = Files.newOutputStream(path); reader = new PdfReader(dirName + "OEWorksheet" + templateName + ".pdf"); original = reader.getSafeFile(); form = reader.getAcroFields(); if (form.getField("capacity") != null) formCapacity = Integer.parseInt(form.getField("capacity")); if (form.getField("diagram_capacity") != null) diagramCapacity = Integer.parseInt(form.getField("diagram_capacity")); else diagramCapacity = formCapacity; doc = new Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(doc, out); doc.open(); reader.close(); i = -1; pageNumber = -1; form = null; page = null; stamper = null; wVDO = wMan.getWorksheet(); for (WorksheetItemDO wiDO : WorksheetManager1Accessor.getItems(wMan)) { j = wiDO.getPosition() % diagramCapacity; if (j == 0) j = diagramCapacity; for (WorksheetAnalysisViewDO waVDO : waVDOMap.get(wiDO.getId())) { if (i == -1 || i > formCapacity || j > diagramCapacity) { if (i != -1) { fillReagentFields(form, wMan); stamper.setFormFlattening(true); renameFields(form, pageNumber); flattenFilledFields(stamper, form, formCapacity, pageNumber); stamper.close(); reader.close(); reader = new PdfReader(page.toByteArray()); writer.addPage(writer.getImportedPage(reader, 1)); reader.close(); } reader = new PdfReader(original, null); page = new ByteArrayOutputStream(); stamper = new PdfStamper(reader, page); form = stamper.getAcroFields(); i = 1; pageNumber++; form.setField("current_date_time", now); form.setField("username", userName); form.setField("worksheet_description_1", wVDO.getDescription()); } qcLink = ""; if (waVDO.getWorksheetAnalysisId() != null) { try { waDO1 = worksheetAnalysis.fetchById(waVDO.getWorksheetAnalysisId()); wiDO1 = worksheetItem.fetchById(waDO1.getWorksheetItemId()); qcLink = waDO1.getAccessionNumber() + " (" + wiDO1.getPosition() + ")"; } catch (Exception anyE) { log.log(Level.SEVERE, anyE.getMessage(), anyE); } } form.setField("worksheet_id_" + (i), wVDO.getId().toString()); form.setField("created_date_" + (i), ReportUtil.toString(wVDO.getCreatedDate(), Messages.get().dateTimePattern())); if (waVDOMap.get(wiDO.getId()).indexOf(waVDO) == 0) form.setField("position_" + (i), wiDO.getPosition().toString()); if (waVDO.getAnalysisId() != null) { sMan = sMap.get(waVDO.getAnalysisId()); sDO = sMan.getSample(); patDO = null; proDO = null; seDO = null; if (Constants.domain().CLINICAL.equals(sDO.getDomain())) { patDO = sMan.getSampleClinical().getPatient(); proDO = sMan.getSampleClinical().getProvider(); } else if (Constants.domain().NEONATAL.equals(sDO.getDomain())) { patDO = sMan.getSampleNeonatal().getPatient(); proDO = sMan.getSampleNeonatal().getProvider(); } else if (Constants.domain().ENVIRONMENTAL.equals(sDO.getDomain())) { seDO = sMan.getSampleEnvironmental(); } sOrgs = SampleManager1Accessor.getOrganizations(sMan); aVDO = (AnalysisViewDO) sMan.getObject(Constants.uid().getAnalysis(waVDO.getAnalysisId())); siVDO = (SampleItemViewDO) sMan .getObject(Constants.uid().getSampleItem(aVDO.getSampleItemId())); sQaevents = new StringBuilder(); sqeVDOs = SampleManager1Accessor.getSampleQAs(sMan); if (sqeVDOs != null && sqeVDOs.size() > 0) { for (SampleQaEventViewDO sqeVDO : sqeVDOs) { if (sQaevents.length() > 0) sQaevents.append(" | "); sQaevents.append(sqeVDO.getQaEventName()); } } aQaevents = new StringBuilder(); aqeVDOs = SampleManager1Accessor.getAnalysisQAs(sMan); if (aqeVDOs != null && aqeVDOs.size() > 0) { for (AnalysisQaEventViewDO aqeVDO : aqeVDOs) { if (!waVDO.getAnalysisId().equals(aqeVDO.getAnalysisId())) continue; if (aQaevents.length() > 0) aQaevents.append(" | "); aQaevents.append(aqeVDO.getQaEventName()); } } sNotes = new StringBuilder(); nVDOs = new ArrayList<NoteViewDO>(); if (SampleManager1Accessor.getSampleInternalNotes(sMan) != null) nVDOs.addAll(SampleManager1Accessor.getSampleInternalNotes(sMan)); if (SampleManager1Accessor.getSampleExternalNote(sMan) != null) nVDOs.add(SampleManager1Accessor.getSampleExternalNote(sMan)); if (nVDOs != null && nVDOs.size() > 0) { for (NoteViewDO nVDO : nVDOs) { if (sNotes.length() > 0) sNotes.append(" | "); sNotes.append(nVDO.getText()); } } aNotes = new StringBuilder(); nVDOs = new ArrayList<NoteViewDO>(); if (SampleManager1Accessor.getAnalysisInternalNotes(sMan) != null) nVDOs.addAll(SampleManager1Accessor.getAnalysisInternalNotes(sMan)); if (SampleManager1Accessor.getAnalysisExternalNotes(sMan) != null) nVDOs.addAll(SampleManager1Accessor.getAnalysisExternalNotes(sMan)); if (nVDOs != null && nVDOs.size() > 0) { for (NoteViewDO nVDO : nVDOs) { if (!waVDO.getAnalysisId().equals(nVDO.getReferenceId())) continue; if (aNotes.length() > 0) aNotes.append(" | "); aNotes.append(nVDO.getText()); } } if (waVDOMap.get(wiDO.getId()).size() > 1) form.setField("well_label_" + (j), wiDO.getPosition().toString()); else form.setField("well_label_" + (j), sDO.getAccessionNumber().toString()); form.setField("accession_number_" + (i), sDO.getAccessionNumber().toString()); form.setField("qc_link_" + (i), qcLink); if (sDO.getCollectionDate() != null) { collectionDateTime = ReportUtil.toString(sDO.getCollectionDate(), Messages.get().datePattern()); if (sDO.getCollectionTime() != null) { collectionDateTime += " "; collectionDateTime += ReportUtil.toString(sDO.getCollectionTime(), Messages.get().timePattern()); } form.setField("collection_date_" + (i), collectionDateTime); } form.setField("received_date_" + (i), ReportUtil.toString(sDO.getReceivedDate(), Messages.get().dateTimePattern())); if (patDO != null) { form.setField("patient_last_" + (i), patDO.getLastName()); form.setField("patient_first_" + (i), patDO.getFirstName()); } if (proDO != null) { form.setField("provider_last_" + (i), proDO.getLastName()); form.setField("provider_first_" + (i), proDO.getFirstName()); } if (seDO != null) { form.setField("env_location_" + (i), seDO.getLocation()); form.setField("env_description_" + (i), seDO.getDescription()); } if (sOrgs != null && sOrgs.size() > 0) { for (SampleOrganizationViewDO soVDO : sOrgs) { if (Constants.dictionary().ORG_REPORT_TO.equals(soVDO.getTypeId())) form.setField("organization_name_" + (i), soVDO.getOrganizationName()); else if (Constants.dictionary().ORG_BILL_TO.equals(soVDO.getTypeId())) form.setField("bill_to_name_" + (i), soVDO.getOrganizationName()); } } form.setField("type_of_sample_" + (i), siVDO.getTypeOfSample()); form.setField("source_of_sample_" + (i), siVDO.getSourceOfSample()); form.setField("source_other_" + (i), siVDO.getSourceOther()); form.setField("container_reference_" + (i), siVDO.getContainerReference()); form.setField("test_" + (i), aVDO.getTestName()); form.setField("method_" + (i), aVDO.getMethodName()); form.setField("sample_qaevent_" + (i), sQaevents.toString()); form.setField("analysis_qaevent_" + (i), aQaevents.toString()); form.setField("sample_note_" + (i), sNotes.toString()); form.setField("analysis_note_" + (i), aNotes.toString()); } else if (waVDO.getQcLotId() != null) { qlVDO = qlMap.get(waVDO.getQcLotId()); form.setField("well_label_" + (j), qlVDO.getQcName()); form.setField("qc_link_" + (i), qcLink); form.setField("qc_name_" + (i), qlVDO.getQcName()); form.setField("qc_lot_" + (i), qlVDO.getLotNumber()); form.setField("qc_usable_" + (i), ReportUtil.toString(qlVDO.getUsableDate(), Messages.get().dateTimePattern())); form.setField("qc_expiration_" + (i), ReportUtil.toString(qlVDO.getExpireDate(), Messages.get().dateTimePattern())); qaVDOs = qaVDOMap.get(qlVDO.getQcId()); if (qaVDOs != null && !qaVDOs.isEmpty()) form.setField("qc_expected_value_" + (i), qaVDOs.get(0).getValue()); } i++; } } fillReagentFields(form, wMan); stamper.setFormFlattening(true); renameFields(form, pageNumber); flattenFilledFields(stamper, form, formCapacity, pageNumber); stamper.close(); reader.close(); reader = new PdfReader(page.toByteArray()); writer.addPage(writer.getImportedPage(reader, 1)); doc.close(); reader.close(); } finally { try { if (out != null) out.close(); } catch (Exception e) { log.severe("Could not close output stream for worksheet print report"); } } return path; }
From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java
License:Open Source License
protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config, OutputStream outputStream) { final org.dom4j.Document configDocument = readCacheInputAsDOM4J(pipelineContext, "model");// TODO: after all, should we use "config"? final org.dom4j.Document instanceDocument = readInputAsDOM4J(pipelineContext, input); final Configuration configuration = XPathCache.getGlobalConfiguration(); final DocumentInfo configDocumentInfo = new DocumentWrapper(configDocument, null, configuration); final DocumentInfo instanceDocumentInfo = new DocumentWrapper(instanceDocument, null, configuration); try {/*from ww w. j a v a 2 s . c o m*/ // Get reader final String templateHref = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@href", null, null, functionLibrary, null, null, null);//TODO: LocationData // Create PDF reader final PdfReader reader; { final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(templateHref); if (inputName != null) { // Read the input final ByteArrayOutputStream os = new ByteArrayOutputStream(); readInputAsSAX(pipelineContext, inputName, new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false)); // Create the reader reader = new PdfReader(os.toByteArray()); } else { // Read and create the reader reader = new PdfReader(URLFactory.createURL(templateHref)); } } // Get total number of pages final int pageCount = reader.getNumberOfPages(); // Get size of first page final Rectangle pageSize = reader.getPageSize(1); final float width = pageSize.getWidth(); final float height = pageSize.getHeight(); final String showGrid = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@show-grid", null, null, functionLibrary, null, null, null);//TODO: LocationData final PdfStamper stamper = new PdfStamper(reader, outputStream); stamper.setFormFlattening(true); for (int currentPage = 1; currentPage <= pageCount; currentPage++) { final PdfContentByte contentByte = stamper.getOverContent(currentPage); // Handle root group final GroupContext initialGroupContext = new GroupContext(contentByte, stamper.getAcroFields(), height, currentPage, Collections.singletonList((Item) instanceDocumentInfo), 1, 0, 0, "Courier", 14, 15.9f); handleGroup(pipelineContext, initialGroupContext, Dom4jUtils.elements(configDocument.getRootElement()), functionLibrary, reader); // Handle preview grid (NOTE: This can be heavy in memory.) if ("true".equalsIgnoreCase(showGrid)) { final float topPosition = 10f; final BaseFont baseFont2 = BaseFont.createFont("Courier", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); contentByte.beginText(); { // 20-pixel lines and side legends contentByte.setFontAndSize(baseFont2, (float) 7); for (int w = 0; w <= width; w += 20) { for (int h = 0; h <= height; h += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int h = 0; h <= height; h += 20) { for (int w = 0; w <= width; w += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int w = 0; w <= width; w += 20) { contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, height - topPosition, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, topPosition, 0); } for (int h = 0; h <= height; h += 20) { contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, (float) 5, height - h, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, width - (float) 5, height - h, 0); } // 10-pixel lines contentByte.setFontAndSize(baseFont2, (float) 3); for (int w = 10; w <= width; w += 10) { for (int h = 0; h <= height; h += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int h = 10; h <= height; h += 10) { for (int w = 0; w <= width; w += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } } contentByte.endText(); } } // Close the document // document.close(); stamper.close(); } catch (Exception e) { throw new OXFException(e); } }
From source file:org.oscarehr.common.printing.HtmlToPdfServlet.java
License:Open Source License
public static byte[] stamp(byte[] content) throws Exception { PdfReader reader = null;// w w w . ja va 2 s. c om ByteArrayOutputStream os = null; PdfStamper stamper = null; try { reader = new PdfReader(content); os = new ByteArrayOutputStream(content.length); stamper = new PdfStamper(reader, os); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte over = stamper.getOverContent(i); BaseFont font = FontSettings.HELVETICA_6PT.createFont(); over.setFontAndSize(font, 10); float center = reader.getPageSize(i).getWidth() / 2.0f; // TODO Consider refactoring this into is own class printText(over, "Page " + i + " of " + reader.getNumberOfPages(), center, 35); printText(over, OscarProperties.getConfidentialityStatement(), center, 25); } // this is ugly, but there is no flush method for readers in itext.... stamper.close(); reader.close(); os.flush(); return os.toByteArray(); } finally { if (os != null) IOUtils.closeQuietly(os); } }
From source file:org.pdfsam.console.business.pdf.handlers.interfaces.AbstractCmdExecutor.java
License:Open Source License
/** * Close the @link {@link PdfStamper} if not null. * /*from www .j a v a2s. c o m*/ * @param pdfStamper */ protected void closePdfStamper(PdfStamper pdfStamper) { if (pdfStamper != null) { try { pdfStamper.close(); } catch (Exception e) { LOG.error("An error occured closing the PdfStamper.", e); } pdfStamper = null; } }