List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
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 w w . j a va2s .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.opensignature.opensignpdf.PDFSigner.java
License:Open Source License
/** * /*from ww w . ja v a2 s . c o m*/ * @param pdfFile * @return * @throws IOException * @throws DocumentException * @throws FileNotFoundException */ private PdfReader createPDFReader(File pdfFile) throws IOException, DocumentException, FileNotFoundException { logger.info("[createPDFReader.in]:: " + Arrays.asList(new Object[] { pdfFile })); PdfReader reader; if ("true".equals(openOfficeSelected)) { String fileName = pdfFile.getPath(); String tempFileName = fileName + ".temp"; PdfReader documentPDF = new PdfReader(fileName); PdfStamperOSP stamperTemp = new PdfStamperOSP(documentPDF, new FileOutputStream(tempFileName)); AcroFields af = stamperTemp.getAcroFields(); af.setGenerateAppearances(true); PdfDictionary acro = (PdfDictionary) PdfReader .getPdfObject(documentPDF.getCatalog().get(PdfName.ACROFORM)); acro.remove(PdfName.DR); HashMap fields = af.getFields(); String key; for (Iterator it = fields.keySet().iterator(); it.hasNext();) { key = (String) it.next(); int a = af.getFieldType(key); if (a == 4) { ArrayList widgets = af.getFieldItem(key).widgets; PdfDictionary widget = (PdfDictionary) widgets.get(0); widget.put(PdfName.FT, new PdfName("Sig")); widget.remove(PdfName.V); widget.remove(PdfName.DV); widget.remove(PdfName.TU); widget.remove(PdfName.FF); widget.remove(PdfName.DA); widget.remove(PdfName.DR); widget.remove(PdfName.AP); } } stamperTemp.close(); documentPDF.close(); reader = new PdfReader(pdfFile.getPath() + ".temp"); } else { reader = new PdfReader(pdfFile.getPath()); } logger.info("[createPDFReader.retorna]:: "); return reader; }
From source file:org.opensignature.opensignpdf.tools.Pkcs7Extractor.java
License:Open Source License
/** * @param args/* w w w.j ava2 s .co m*/ */ public static void main(String[] args) { // TODO Auto-generated method stub try { if (args.length < 1) { System.out.println("Usage: EstraiPkcs7 <pdf file relative to current dir>"); System.exit(1); } String filename = args[0]; PdfReader reader = new PdfReader(filename); 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("Signature covers whole document: " + af.signatureCoversWholeDocument(name)); System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions()); // Start revision extraction // FileOutputStream out = new FileOutputStream("revision_" + // af.getRevision(name) + ".pdf"); // byte bb[] = new byte[8192]; // InputStream ip = af.extractRevision(name); // int n = 0; // while ((n = ip.read(bb)) > 0) // out.write(bb, 0, n); // out.close(); // ip.close(); // End revision extraction // PdfPKCS7 pk = af.verifySignature(name); PdfDictionary v = af.getSignatureDictionary(name); PdfString contents = (PdfString) PdfReader.getPdfObject(v.get(PdfName.CONTENTS)); // Start pkcs7 extraction FileOutputStream fos = new FileOutputStream(filename + "_signeddata_" + name + ".pk7"); System.out.println(k + ") Estrazione pkcs7: " + filename + "_signeddata_" + name + ".pk7"); fos.write(contents.getOriginalBytes()); fos.flush(); fos.close(); // End pkcs7 extraction /* Commentato per evitare dipendenze da BC Security.insertProviderAt(new BouncyCastleProvider(), 3); // nota: dipendenza da provider BC per "SHA1withRSA" PdfPKCS7 pk = new PdfPKCS7(contents.getOriginalBytes(), "BC"); Calendar cal = pk.getSignDate(); Certificate pkc[] = pk.getCertificates(); System.out.println("Got " + pkc.length + " certificates from pdf"); System.out .println("Subject of signer: " + PdfPKCS7.getSubjectFields(pk .getSigningCertificate())); // System.out.println("Document modified: " + !pk.verify()); // Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, // cal); // if (fails == null) // System.out.println("Certificates verified against the // KeyStore"); // else // System.out.println("Certificate failed: " + fails[1]); */ } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* decommentare se si riabilita la parte relativa a PdfPKCS7 nel main catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CRLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ }
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 w w w. j a va2s. 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 . j a v a 2 s . c o m 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.oscarehr.common.printing.HtmlToPdfServlet.java
License:Open Source License
private static void appendFooter(byte[] pdf, ByteArrayOutputStream baos) { PdfReader reader = null;/*from www . j av a 2 s .co m*/ PdfWriter writer = null; Document document = null; try { // do initialization reader = new PdfReader(pdf); document = new Document(PageSize.LETTER); writer = PdfWriterFactory.newInstance(document, baos, FontSettings.HELVETICA_6PT); document.open(); PdfContentByte cb = writer.getDirectContent(); // copy pages for (int i = 1; i <= reader.getNumberOfPages(); i++) { cb.addTemplate(writer.getImportedPage(reader, i), 0, 0); } } catch (Exception e) { throw new RuntimeException("Unable to append document footer", e); } finally { close(document); close(writer); close(reader); } }
From source file:org.oscarehr.document.web.ManageDocumentAction.java
License:Open Source License
public ActionForward getDocPageNumber(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/*www. java 2 s .c om*/ String doc_no = request.getParameter("doc_no"); Document d = documentDAO.getDocument(doc_no); String filePath = EDocUtil.getDocumentPath(d.getDocfilename()); int numOfPage = 0; try { PdfReader reader = new PdfReader(filePath); numOfPage = reader.getNumberOfPages(); HashMap hm = new HashMap(); hm.put("numOfPage", numOfPage); JSONObject jsonObject = JSONObject.fromObject(hm); response.getOutputStream().write(jsonObject.toString().getBytes()); } catch (IOException e) { MiscUtils.getLogger().error("Error", e); } return null;// execute2(mapping, form, request, response); }
From source file:org.oscarehr.phr.web.PHRUserManagementAction.java
License:Open Source License
public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username, String password) throws Exception { log.debug("Demographic " + demographicNo + " username " + username + " password " + password); DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao"); Demographic demographic = demographicDao.getDemographic(demographicNo); final String PAGESIZE = "printPageSize"; Document document = new Document(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null;/*w ww . jav a2s . c o m*/ try { writer = PdfWriter.getInstance(document, baosPDF); String title = "TITLE"; String template = "MyOscarLetterHead.pdf"; Properties printCfg = getCfgProp(); String[] cfgVal = null; StringBuilder tempName = null; // get the print prop values Properties props = new Properties(); props.setProperty("letterDate", UtilDateUtilities.getToday("yyyy-MM-dd")); props.setProperty("name", demographic.getFirstName() + " " + demographic.getLastName()); props.setProperty("dearname", demographic.getFirstName() + " " + demographic.getLastName()); props.setProperty("address", demographic.getAddress()); props.setProperty("city", demographic.getCity() + ", " + demographic.getProvince()); props.setProperty("postalCode", demographic.getPostal()); props.setProperty("credHeading", "MyOscar User Account Details"); props.setProperty("username", "Username: " + username); props.setProperty("password", "Password: " + password); //Temporary - the intro will change to be dynamic props.setProperty("intro", "We are pleased to provide you with a log in and password for your new MyOSCAR Personal Health Record. This account will allow you to connect electronically with our clinic. Please take a few minutes to review the accompanying literature for further information.We look forward to you benefiting from this service."); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); Rectangle pageSize = PageSize.LETTER; document.setPageSize(pageSize); document.open(); // create a reader for a certain document String propFilename = oscar.OscarProperties.getInstance().getProperty("pdfFORMDIR", "") + "/" + template; PdfReader reader = null; try { reader = new PdfReader(propFilename); log.debug("Found template at " + propFilename); } catch (Exception dex) { log.debug("change path to inside oscar from :" + propFilename); reader = new PdfReader("/oscar/form/prop/" + template); log.debug("Found template at /oscar/form/prop/" + template); } // retrieve the total number of pages int n = reader.getNumberOfPages(); // retrieve the size of the first page Rectangle pSize = reader.getPageSize(1); float width = pSize.getWidth(); float height = pSize.getHeight(); log.debug("Width :" + width + " Height: " + height); PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); int fontFlags = 0; document.newPage(); PdfImportedPage page1 = writer.getImportedPage(reader, 1); cb.addTemplate(page1, 1, 0, 0, 1, 0, 0); BaseFont bf; // = normFont; String encoding; cb.setRGBColorStroke(0, 0, 255); String[] fontType; for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) { tempName = new StringBuilder(e.nextElement().toString()); cfgVal = printCfg.getProperty(tempName.toString()).split(" *, *"); if (cfgVal[4].indexOf(";") > -1) { fontType = cfgVal[4].split(";"); if (fontType[1].trim().equals("italic")) fontFlags = Font.ITALIC; else if (fontType[1].trim().equals("bold")) fontFlags = Font.BOLD; else if (fontType[1].trim().equals("bolditalic")) fontFlags = Font.BOLDITALIC; else fontFlags = Font.NORMAL; } else { fontFlags = Font.NORMAL; fontType = new String[] { cfgVal[4].trim() }; } if (fontType[0].trim().equals("BaseFont.HELVETICA")) { fontType[0] = BaseFont.HELVETICA; encoding = BaseFont.CP1252; //latin1 encoding } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) { fontType[0] = BaseFont.HELVETICA_OBLIQUE; encoding = BaseFont.CP1252; } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) { fontType[0] = BaseFont.ZAPFDINGBATS; encoding = BaseFont.ZAPFDINGBATS; } else { fontType[0] = BaseFont.COURIER; encoding = BaseFont.CP1252; } bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED); // write in a rectangle area if (cfgVal.length >= 9) { Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags); ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()), (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()), (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT : Element.ALIGN_CENTER))); ct.setText(new Phrase(12, props.getProperty(tempName.toString(), ""), font)); ct.go(); continue; } // draw line directly if (tempName.toString().startsWith("__$line")) { cb.setRGBColorStrokeF(0f, 0f, 0f); cb.setLineWidth(Float.parseFloat(cfgVal[4].trim())); cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim())); cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim())); // stroke the lines cb.stroke(); // write text directly } else if (tempName.toString().startsWith("__")) { cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? (cfgVal[6].trim()) : props.getProperty(tempName.toString(), "")), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } else if (tempName.toString().equals("forms_promotext")) { if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) { cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } } else { // write prop text cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? ((props.getProperty(tempName.toString(), "").equals("") ? "" : cfgVal[6].trim())) : props.getProperty(tempName.toString(), "")), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } finally { if (document != null) document.close(); if (writer != null) writer.close(); } return baosPDF; }
From source file:org.oscarehr.research.eaaps.EaapsHandler.java
License:Open Source License
private int countPages(String fileName) { PdfReader reader = null;/*w w w . ja va2s . co m*/ try { reader = new PdfReader(EDocUtil.resovePath(fileName)); return reader.getNumberOfPages(); } catch (IOException e) { logger.debug("Unable to count pages in " + fileName + " due to " + e.getMessage()); } finally { if (reader != null) { reader.close(); } } return -1; }
From source file:org.pdfsam.console.business.pdf.handlers.ConcatCmdExecutor.java
License:Open Source License
/** * Apply pages rotations// ww w . j av a 2 s. c o m * * @param inputFile * @param inputCommand * @return temporary file with pages rotation */ private File applyRotations(File inputFile, ConcatParsedCommand inputCommand) throws Exception { rotationReader = new PdfReader(inputFile.getAbsolutePath()); rotationReader.removeUnusedObjects(); rotationReader.consolidateNamedDestinations(); int pdfNumberOfPages = rotationReader.getNumberOfPages(); PageRotation[] rotations = inputCommand.getRotations(); if (rotations != null && rotations.length > 0) { if (rotations.length > 1) { for (int i = 0; i < rotations.length; i++) { if (pdfNumberOfPages >= rotations[i].getPageNumber() && rotations[i].getPageNumber() > 0) { PdfDictionary dictionary = rotationReader.getPageN(rotations[i].getPageNumber()); int rotation = (rotations[i].getDegrees() + rotationReader.getPageRotation(rotations[i].getPageNumber())) % 360; dictionary.put(PdfName.ROTATE, new PdfNumber(rotation)); } else { LOG.warn("Rotation for page " + rotations[i].getPageNumber() + " ignored."); } } } else { // rotate all if (rotations[0].getType() == PageRotation.ALL_PAGES) { int pageRotation = rotations[0].getDegrees(); for (int i = 1; i <= pdfNumberOfPages; i++) { PdfDictionary dictionary = rotationReader.getPageN(i); int rotation = (pageRotation + rotationReader.getPageRotation(i)) % 360; dictionary.put(PdfName.ROTATE, new PdfNumber(rotation)); } } else if (rotations[0].getType() == PageRotation.SINGLE_PAGE) { // single page rotation if (pdfNumberOfPages >= rotations[0].getPageNumber() && rotations[0].getPageNumber() > 0) { PdfDictionary dictionary = rotationReader.getPageN(rotations[0].getPageNumber()); int rotation = (rotations[0].getDegrees() + rotationReader.getPageRotation(rotations[0].getPageNumber())) % 360; dictionary.put(PdfName.ROTATE, new PdfNumber(rotation)); } else { LOG.warn("Rotation for page " + rotations[0].getPageNumber() + " ignored."); } } else if (rotations[0].getType() == PageRotation.ODD_PAGES) { // odd pages rotation int pageRotation = rotations[0].getDegrees(); for (int i = 1; i <= pdfNumberOfPages; i = i + 2) { PdfDictionary dictionary = rotationReader.getPageN(i); int rotation = (pageRotation + rotationReader.getPageRotation(i)) % 360; dictionary.put(PdfName.ROTATE, new PdfNumber(rotation)); } } else if (rotations[0].getType() == PageRotation.EVEN_PAGES) { // even pages rotation int pageRotation = rotations[0].getDegrees(); for (int i = 2; i <= pdfNumberOfPages; i = i + 2) { PdfDictionary dictionary = rotationReader.getPageN(i); int rotation = (pageRotation + rotationReader.getPageRotation(i)) % 360; dictionary.put(PdfName.ROTATE, new PdfNumber(rotation)); } } else { LOG.warn("Unable to find the rotation type. " + rotations[0]); } } LOG.info("Pages rotation applied."); } File rotatedTmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); Character pdfVersion = inputCommand.getOutputPdfVersion(); if (pdfVersion != null) { rotationStamper = new PdfStamper(rotationReader, new FileOutputStream(rotatedTmpFile), inputCommand.getOutputPdfVersion().charValue()); } else { rotationStamper = new PdfStamper(rotationReader, new FileOutputStream(rotatedTmpFile), rotationReader.getPdfVersion()); } HashMap meta = rotationReader.getInfo(); meta.put("Creator", ConsoleServicesFacade.CREATOR); setCompressionSettingOnStamper(inputCommand, rotationStamper); rotationStamper.setMoreInfo(meta); rotationStamper.close(); rotationReader.close(); return rotatedTmpFile; }