List of usage examples for com.lowagie.text.pdf PdfWriter getInstance
public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException
PdfWriter
. From source file:de.tr1.cooperator.manager.web.CreateSubscriberListAction.java
License:Open Source License
/** * This method is called by the struts-framework if the submit-button is pressed. * It creates a PDF-File and puts in into the output-stream of the response. *///from ww w . j a v a 2 s . c o m public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CreateSubscriberListForm myForm = (CreateSubscriberListForm) form; boolean bSortByName; if (myForm.getSortBy().equals(myForm.SORTBYPN)) bSortByName = false; else bSortByName = true; //create Collection for the results... Event eEvent = EventManager.getInstance().getEventByID(myForm.getEventID()); Collection cSubscriberList = UserManager.getInstance().getUsersByCollection(eEvent.getSubscriberList()); Collection cExamResults = EventResultManager.getInstance().getResults(eEvent.getID()); Iterator cSubscriberListIT = cSubscriberList.iterator(); Collection cSubscriberResultList = new ArrayList(); while (cSubscriberListIT.hasNext()) { User CurUser = (User) cSubscriberListIT.next(); String UserPNR = CurUser.getPersonalNumber(); Iterator cExamResultsIT = cExamResults.iterator(); ExamResult curExamResult = null; String ResultUserPNR = null; while (cExamResultsIT.hasNext()) { curExamResult = (ExamResult) cExamResultsIT.next(); ResultUserPNR = curExamResult.getUserPersonalNumber(); if (UserPNR.equals(ResultUserPNR)) break; } if (UserPNR.equals(ResultUserPNR)) { if (bSortByName) { UserResultSortByName URS = new UserResultSortByName(CurUser, "" + curExamResult.getResult()); cSubscriberResultList.add(URS); } else { UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "" + curExamResult.getResult()); cSubscriberResultList.add(URS); } } else { if (bSortByName) { UserResultSortByName URS = new UserResultSortByName(CurUser, "-"); cSubscriberResultList.add(URS); } else { UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "-"); cSubscriberResultList.add(URS); } } } //sort List Collections.sort((List) cSubscriberResultList); BaseFont bf; //36pt = 0.5inch Document document = new Document(PageSize.A4, 36, 36, 72, 72); try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); } catch (Exception e) { Log.addLog("CreateSubscriberListAction: Error creating BaseFont: " + e); //2do: add ErrorMessage and return to inputFormular! return mapping.findForward("GeneralFailure"); } //calculate the number of cols and their width int cols = 0; ArrayList alWidth = new ArrayList(); float boldItalicFactor = 1.2f; if (myForm.getShowNumber()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NUMBER, TABLEHEADER_FONTSIZE))); if (myForm.getShowPersonalNumber()) alWidth.add(new Float( boldItalicFactor * bf.getWidthPoint(TABLEHEADER_PERSONALNUMBER, TABLEHEADER_FONTSIZE))); if (myForm.getShowName()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NAME, TABLEHEADER_FONTSIZE))); if (myForm.getShowEmail()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_EMAIL, TABLEHEADER_FONTSIZE))); if (myForm.getShowResult()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_RESULT, TABLEHEADER_FONTSIZE))); if (myForm.getAddInfoField()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_INFO, TABLEHEADER_FONTSIZE))); if (myForm.getAddSignField()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_SIGN, TABLEHEADER_FONTSIZE))); cols = alWidth.size(); float totalWidth = 0; //calculate the whole length Iterator alIterator = alWidth.iterator(); for (; alIterator.hasNext(); totalWidth += ((Float) alIterator.next()).floatValue()) ; //calculate relativ width for the table float[] width = new float[cols]; alIterator = alWidth.iterator(); int i = 0; while (alIterator.hasNext()) { float pixLength = ((Float) alIterator.next()).floatValue(); //alWidthRelativ.add( new Float( pixLength/totalWidth ) ); width[i] = pixLength / totalWidth; i++; } //needed for the shrink (enlarge?) float shrinkFactor; try { //1st: set correct outputstream PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); //1.5st: set content-stuff response.setContentType("application/pdf"); //2nd: set EventManager for PageEvents to Helper writer.setPageEvent( new CreateSubscriberListActionHelper(myForm.getHeaderLeft(), myForm.getHeaderRight())); //3rd: open document for editing the content document.open(); //4th: add content Phrase pInfoText = new Phrase(myForm.getInfoText(), new Font(bf, 12, Font.BOLD)); document.add(pInfoText); //PdfPTable( cols ) PdfPTable table = new PdfPTable(width); float documentWidth = document.right() - document.left(); if (documentWidth < totalWidth) { table.setTotalWidth(documentWidth); shrinkFactor = documentWidth / totalWidth; } else { table.setTotalWidth(totalWidth); shrinkFactor = 1; } table.setLockedWidth(true); Font headerFont = new Font(bf, TABLEHEADER_FONTSIZE * shrinkFactor, Font.BOLDITALIC); Font cellFont = new Font(bf, TABLECELL_FONTSIZE * shrinkFactor, Font.NORMAL); if (myForm.getShowNumber()) table.addCell(new Phrase(TABLEHEADER_NUMBER, headerFont)); if (myForm.getShowPersonalNumber()) table.addCell(new Phrase(TABLEHEADER_PERSONALNUMBER, headerFont)); if (myForm.getShowName()) table.addCell(new Phrase(TABLEHEADER_NAME, headerFont)); if (myForm.getShowEmail()) table.addCell(new Phrase(TABLEHEADER_EMAIL, headerFont)); if (myForm.getShowResult()) table.addCell(new Phrase(TABLEHEADER_RESULT, headerFont)); if (myForm.getAddInfoField()) table.addCell(new Phrase(TABLEHEADER_INFO, headerFont)); if (myForm.getAddSignField()) table.addCell(new Phrase(TABLEHEADER_SIGN, headerFont)); //fill table Iterator iSRL = cSubscriberResultList.iterator(); int counter = 1; while (iSRL.hasNext()) { UserResult curResult = (UserResult) iSRL.next(); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); if (myForm.getShowNumber()) table.addCell(new Phrase("" + counter++, cellFont)); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); if (myForm.getShowPersonalNumber()) table.addCell(new Phrase(curResult.getPersonalNumber(), cellFont)); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); if (myForm.getShowName()) table.addCell(new Phrase(curResult.getSurname() + ", " + curResult.getFirstName(), cellFont)); if (myForm.getShowEmail()) table.addCell(new Phrase(curResult.getEmailAddress(), cellFont)); if (myForm.getShowResult()) table.addCell(new Phrase(curResult.getResult(), cellFont)); if (myForm.getAddInfoField()) table.addCell(new Phrase("", cellFont)); if (myForm.getAddSignField()) table.addCell(new Phrase("", cellFont)); } //set how many rows are header... table.setHeaderRows(1); document.add(table); //5th: close document, write the output to the stream... document.close(); } catch (Exception de) { Log.addLog("CreateSubscriberListAction: Error creating PDF: " + de); } //we dont need to return a forward, because we write directly to the outputstream! return null; }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/** * Creates the pdf writer./* ww w .j a va2s . c o m*/ * * @param out the out * @param writer the writer * @param pdfdoc the pdfdoc * * @return the pdf writer * * @throws PDFManagerException the PDF manager exception */ private PdfWriter createPDFWriter(OutputStream out, Document pdfdoc) throws PDFManagerException { PdfWriter writer = null; try { // open the pdfwriter using the outstream writer = PdfWriter.getInstance(pdfdoc, out); LOGGER.debug("PDFWriter intstantiated"); // register Fonts int numoffonts = FontFactory.registerDirectories(); LOGGER.debug(numoffonts + " fonts found and registered!"); if ((pdfa) && (iccprofile != null)) { // we want to write PDFA, we have to set the PDFX conformance // before we open the writer writer.setPDFXConformance(PdfWriter.PDFA1B); } // open the pdf document to add pages and other content try { pdfdoc.open(); LOGGER.debug("PDFDocument opened"); } catch (Exception e) { throw new PDFManagerException("PdfWriter was opened, but the pdf document couldn't be opened", e); } if ((pdfa) && (iccprofile != null)) { // set the required PDFDictionary which // contains the appropriate ICC profile PdfDictionary pdfdict_out = new PdfDictionary(PdfName.OUTPUTINTENT); // set identifier for ICC profile pdfdict_out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGBIEC61966-2.1")); pdfdict_out.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); pdfdict_out.put(PdfName.S, PdfName.GTS_PDFA1); // PdfICCBased ib = new PdfICCBased(iccprofile); // writer.setOutputIntents("Custom", "PDF/A sRGB", null, "PDF/A // sRGB ICC Profile, sRGB_IEC61966-2-1_withBPC.icc", // colorProfileData); // read icc profile // ICC_Profile icc = ICC_Profile.getInstance(new // FileInputStream("c:\\srgb.profile")); PdfICCBased ib = new PdfICCBased(iccprofile); ib.remove(PdfName.ALTERNATE); PdfIndirectObject pio = writer.addToBody(ib); pdfdict_out.put(PdfName.DESTOUTPUTPROFILE, pio.getIndirectReference()); writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(pdfdict_out)); // create MarkInfo elements // not sure this is necessary; maybe just needed for tagged PDFs // (PDF/A 1a) PdfDictionary markInfo = new PdfDictionary(PdfName.MARKINFO); markInfo.put(PdfName.MARKED, new PdfBoolean("false")); writer.getExtraCatalog().put(PdfName.MARKINFO, markInfo); // write XMP this.writeXMPMetadata(writer); } } catch (Exception e) { LOGGER.error("Can't open the PdfWriter object\n" + e.toString() + "\n" + e.getMessage()); throw new PDFManagerException("Can't open the PdfWriter object", e); } return writer; }
From source file:de.xirp.chart.ChartUtil.java
License:Open Source License
/** * Exports the given chart as PDF in the specified size. The * export is written to the given path.//from w ww .j a v a2s .co m * * @param chart * The chart to export. * @param width * The desired width of the PDF. * @param height * The desired height of the PDF. * @param path * The path to write the PDF to. * @see org.jfree.chart.JFreeChart */ private static void exportPDF(JFreeChart chart, int width, int height, String path) { Document document = new Document(new Rectangle(width, height)); try { PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(path)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2d, r2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); } catch (Exception e) { logClass.error("Error: " + e.getMessage() //$NON-NLS-1$ + Constants.LINE_SEPARATOR, e); } document.close(); }
From source file:de.xirp.report.ReportGenerator.java
License:Open Source License
/** * Generates the PDF from the/*w ww. j a v a 2s.com*/ * {@link de.xirp.report.Report} and writes the PDF * to a file. <br> * <br> * At first the title and header pages are created. After that the * content pages are created. * * @return The file name of the PDF. * @throws IOException * if something went wrong saving the PDF. * @throws DocumentException * if something went wrong generating the PDF. * @throws MalformedURLException * if something went wrong saving the PDF. * @see de.xirp.report.Report */ private static String generatePDF() throws DocumentException, MalformedURLException, IOException { String filename = report.getName().replaceAll(" ", "-") + "_report_" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + report.getHeader().getRobot().getName() + "_" //$NON-NLS-1$ + Util.getTimeAsString(report.getHeader().getDate()) + ".pdf"; //$NON-NLS-1$ reportFile = new File(Constants.REPORT_DIR + File.separator + filename); // creation of a document-object document = new Document(PageSize.A4); // we create a writer that listens to the document // and directs a PDF-stream to a file writer = PdfWriter.getInstance(document, new FileOutputStream(reportFile.getPath())); writer.setPdfVersion(PdfWriter.VERSION_1_7); writer.setStrictImageSequence(true); // open the document document.open(); // add the title page addReportTitle(); addReportContent(); // close the document document.close(); return filename; }
From source file:demo.dwr.simple.UploadDownload.java
License:Apache License
/** * Generates a PDF file with the given text * http://itext.ugent.be/itext-in-action/ * @return A PDF file as a byte array//from ww w. j a va 2s . c o m */ public FileTransfer downloadPdfFile(String contents) throws Exception { if (contents == null || contents.length() == 0) { contents = "[BLANK]"; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, buffer); // ?itext-asian BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); // ?WINDOW c:\windows\Fonts\xxx.ttf // ?classpath: /src/main/resources/fonts/simsong.ttf Font fontChinese = new Font(bfChinese, 12, Font.NORMAL); document.addCreator("DWR.war using iText"); document.open(); document.add(new Paragraph(contents, fontChinese)); document.close(); return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray()); }
From source file:desktopbugtracker.export.PdfInitializer.java
License:Open Source License
public Document getDocument() throws PdfExportException { Document document = null;//from w ww . ja v a 2s. co m try { document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); } catch (DocumentException ex) { throw new PdfExportException(ex); } catch (FileNotFoundException ex) { throw new PdfExportException(ex); } return document; }
From source file:dinamica.AbstractPDFOutput.java
License:LGPL
/** * Receives a byte buffer that should be filled with resulting PDF. * @param data Data module that provides recordsets to this output module * @param buf Buffer to print PDF, then used to send to browser * @throws Throwable/*from w w w . j a v a 2 s . c om*/ */ protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable { //pdf objects Document doc = new Document(); PdfWriter docWriter = PdfWriter.getInstance(doc, buf); //header HeaderFooter header = new HeaderFooter(new Phrase(getHeader()), false); header.setBorder(Rectangle.BOTTOM); header.setAlignment(Rectangle.ALIGN_CENTER); doc.setHeader(header); //footer HeaderFooter footer = new HeaderFooter(new Phrase(getFooter()), true); footer.setBorder(Rectangle.TOP); footer.setAlignment(Rectangle.ALIGN_RIGHT); doc.setFooter(footer); //pagesize doc.setPageSize(PageSize.LETTER); doc.open(); //title Paragraph t = new Paragraph(getReportTitle(), new Font(Font.HELVETICA, 18f)); t.setAlignment(Rectangle.ALIGN_CENTER); doc.add(t); //paragraph Paragraph p = new Paragraph("Hello World"); p.setAlignment(Rectangle.ALIGN_CENTER); doc.add(p); doc.close(); docWriter.close(); }
From source file:docet.engine.PDFDocumentHandler.java
License:Apache License
private void createPDF(OutputStream os, int initialPageNo) throws DocetDocumentParsingException { if (documents.isEmpty()) { throw new DocetDocumentParsingException("No available pages to parse"); }//from w ww .j av a 2s . c o m if (initialPageNo < 1) { initialPageNo = 1; } int coversize = 0; DocumentPart cover = null; if (renderCover) { cover = generateCover(); coversize = 1; } int tocsize = 0; DocumentPart toc = null; if (renderToc) { toc = generateTOC(documents.values(), initialPageNo + coversize + 1 /* Cover & TOC part*/); /* Regenerate TOC if more than one page */ if (toc.pages.size() > 1) { toc = generateTOC(documents.values(), initialPageNo + coversize + toc.pages.size()); } tocsize = toc.pages.size(); } int totalPages = documents.values().stream().mapToInt(p -> p.pages.size()).sum() + coversize + tocsize; com.lowagie.text.Document pdf = null; PdfWriter writer = null; try { /* Uses the first page added to evaluate page size and create the writer */ DocumentPart firstSection = documents.values().stream().findFirst().get(); PageBox firstPage = firstSection.pages.get(0); RenderingContext renderingContext = newRenderingContext(firstSection.root); com.lowagie.text.Rectangle firstPageSize = new com.lowagie.text.Rectangle(0, 0, firstPage.getWidth(renderingContext) / dotsPerPoint, firstPage.getHeight(renderingContext) / dotsPerPoint); pdf = new com.lowagie.text.Document(firstPageSize, 0, 0, 0, 0); try { writer = PdfWriter.getInstance(pdf, os); } catch (DocumentException e) { throw new DocetDocumentParsingException("Cannot create a pdf writer", e); } pdf.addTitle(placeholders.get(HTMLPlaceholder.TITLE)); pdf.open(); /* Write each document */ try { if (renderCover) { writePDF(cover, totalPages, pdf, writer); } if (renderToc) { writePDF(toc, totalPages, pdf, writer); } for (DocumentPart part : documents.values()) { writePDF(part, totalPages, pdf, writer); } } catch (DocumentException e) { throw new DocetDocumentParsingException( "Cannot write document " + placeholders.get(HTMLPlaceholder.TITLE) + " to pdf", e); } /* Terminate writing bookmarks with collected pages */ if (renderBookmarks) { writeTOCBookmarks(documents.values(), writer); } } finally { if (pdf != null) { pdf.close(); } if (writer != null) { writer.close(); } } }
From source file:domain.reports.menu.PDFReportMenu.java
License:LGPL
@Override protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable { //inicializar documento: tamano de pagina, orientacion, margenes Document doc = new Document(); PdfWriter docWriter = PdfWriter.getInstance(doc, buf); doc.setPageSize(PageSize.LETTER.rotate()); doc.setMargins(30, 30, 30, 40);//from w w w .j a va 2 s . c o m doc.open(); //crear fonts por defecto tblHeaderFont = new Font(Font.HELVETICA, 10f, Font.BOLD); tblBodyFont = new Font(Font.HELVETICA, 10f, Font.NORMAL); //definir pie de pagina del lado izquierdo String footerText = this.getFooter(); //read it from config.xml or web.xml String reportDate = StringUtil.formatDate(new java.util.Date(), "dd-MM-yyyy HH:mm"); //crear template (objeto interno de IText) y manejador de evento //para imprimir el pie de pagina bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb = docWriter.getDirectContent(); tpl = cb.createTemplate(20, 14); docWriter.setPageEvent(new PDFPageEvents(footerText, pageXofY, tpl, bf, cb, reportDate)); //titulo - lo lee de config.xml por defecto reportTitle = getReportTitle(); Paragraph t = new Paragraph(reportTitle, new Font(Font.HELVETICA, 14f, Font.BOLD)); t.setAlignment(Rectangle.ALIGN_RIGHT); doc.add(t); //logo img = Image.getInstance(getImage(this.getServerBaseURL() + logoPath, false)); img.scalePercent(100); float imgY = doc.top() - img.getHeight(); float imgX = doc.left(); img.setAbsolutePosition(imgX, imgY); doc.add(img); //blank line doc.add(new Paragraph(" ")); //blank line doc.add(new Paragraph(" ")); //blank line doc.add(new Paragraph(" ")); //for each master record print a master/detail section MasterDetailReader dataobj = (MasterDetailReader) data; Recordset master = dataobj.getRecordset("master"); master.top(); while (master.next()) { //blank line doc.add(new Paragraph(" ")); //print master section doc.add(getGroupMaster(master)); //print detail section doc.add(getGroupDetail(master, dataobj.getDetail(master))); } //print grand total doc.add(new Paragraph(" ")); doc.close(); docWriter.close(); }
From source file:dr.app.tracer.analysis.TemporalAnalysisFrame.java
License:Open Source License
public final void doExportPDF() { FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE); dialog.setVisible(true);/*from www . ja va2 s. com*/ if (dialog.getFile() != null) { File file = new File(dialog.getDirectory(), dialog.getFile()); Rectangle2D bounds = temporalAnalysisPlotPanel.getExportableComponent().getBounds(); Document document = new Document( new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight())); try { // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(file)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight()); Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper()); temporalAnalysisPlotPanel.getExportableComponent().print(g2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } document.close(); } }