List of usage examples for com.lowagie.text Document setMargins
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom)
From source file:org.vfny.geoserver.wms.responses.map.pdf.PDFMapProducer.java
License:Open Source License
/** * Writes the image to the client./*from w ww . ja v a 2s . co m*/ * * @param out * The output stream to write to. */ public void writeTo(OutputStream out) throws ServiceException, java.io.IOException { final int width = mapContext.getMapWidth(); final int height = mapContext.getMapHeight(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting up " + width + "x" + height + " image"); } try { // step 1: creation of a document-object // width of document-object is width*72 inches // height of document-object is height*72 inches com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height); Document document = new Document(pageSize); document.setMargins(0, 0, 0, 0); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, out); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it // we create a fontMapper and read all the fonts in the font // directory DefaultFontMapper mapper = new DefaultFontMapper(); FontFactory.registerDirectories(); // we create a template and a Graphics2D object that corresponds // with it PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper); // we set graphics options if (!mapContext.isTransparent()) { graphic.setColor(mapContext.getBgColor()); graphic.fillRect(0, 0, width, height); } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting to transparent"); } int type = AlphaComposite.SRC; graphic.setComposite(AlphaComposite.getInstance(type)); Color c = new Color(mapContext.getBgColor().getRed(), mapContext.getBgColor().getGreen(), mapContext.getBgColor().getBlue(), 0); graphic.setBackground(mapContext.getBgColor()); graphic.setColor(c); graphic.fillRect(0, 0, width, height); type = AlphaComposite.SRC_OVER; graphic.setComposite(AlphaComposite.getInstance(type)); } Rectangle paintArea = new Rectangle(width, height); renderer = new StreamingRenderer(); renderer.setContext(mapContext); // TODO: expose the generalization distance as a param // ((StreamingRenderer) renderer).setGeneralizationDistance(0); RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.setJava2DHints(hints); // we already do everything that the optimized data loading does... // if we set it to true then it does it all twice... Map rendererParams = new HashMap(); rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true)); rendererParams.put("renderingBuffer", new Integer(mapContext.getBuffer())); // we need the renderer to draw everything on the batik provided graphics object rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE); if (!DefaultWebMapService.isLineWidthOptimizationEnabled()) { rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, false); } renderer.setRendererHints(rendererParams); Envelope dataArea = mapContext.getAreaOfInterest(); AffineTransform at = RendererUtilities.worldToScreenTransform(dataArea, paintArea); if (this.abortRequested) { graphic.dispose(); // step 5: we close the document document.close(); return; } // enforce no more than x rendering errors int maxErrors = wms.getMaxRenderingErrors(); MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors); // Add a render listener that ignores well known rendering exceptions and reports back non // ignorable ones final RenderExceptionStrategy nonIgnorableExceptionListener; nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer); renderer.addRenderListener(nonIgnorableExceptionListener); // enforce max memory usage int maxMemory = wms.getMaxRequestMemory() * KB; PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory); // render the map renderer.paint(graphic, paintArea, at); // render the watermark MapDecorationLayout.Block watermark = DefaultRasterMapProducer .getWatermark(this.mapContext.getRequest().getWMS().getServiceInfo()); if (watermark != null) { MapDecorationLayout layout = new MapDecorationLayout(); layout.paint(graphic, paintArea, this.mapContext); } //check if a non ignorable error occurred if (nonIgnorableExceptionListener.exceptionOccurred()) { Exception renderError = nonIgnorableExceptionListener.getException(); throw new WmsException("Rendering process failed", "internalError", renderError); } // check if too many errors occurred if (errorChecker.exceedsMaxErrors()) { throw new WmsException("More than " + maxErrors + " rendering errors occurred, bailing out", "internalError", errorChecker.getLastException()); } // check we did not use too much memory if (memoryChecker.exceedsMaxSize()) { long kbMax = maxMemory / KB; throw new WmsException( "Rendering request used more memory than the maximum allowed:" + kbMax + "KB"); } graphic.dispose(); cb.addTemplate(tp, 0, 0); // step 5: we close the document document.close(); writer.flush(); writer.close(); } catch (DocumentException t) { throw new WmsException("Error setting up the PDF", "internalError", t); } }
From source file:org.webguitoolkit.ui.util.export.PDFTableExport.java
License:Apache License
public void writeTo(Table table, OutputStream out) { TableExportOptions exportOptions = table.getExportOptions(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // set the page orientation Din-A4 Portrait or Landscape Rectangle page = PageSize.A4; if (exportOptions.getPdfPosition() != null && exportOptions.getPdfPosition().equals(TableExportOptions.PDF_LANDSCAPE)) { // landscape position page = PageSize.A4.rotate();//from w w w. j a v a 2 s . com } else if (exportOptions.getPdfPosition() != null && exportOptions.getPdfPosition().equals(TableExportOptions.PDF_PORTRAIT)) { // portrait position page = PageSize.A4; } if (exportOptions.getPdfPageColour() != null) { // page.setBackgroundColor(exportOptions.getPdfPageColour()); } Document document = new Document(page); document.setMargins(36f, 36f, 50f, 40f); try { PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new PDFEvent(table)); document.open(); if (StringUtils.isNotEmpty(exportOptions.getHeadline())) { Font titleFont = new Font(Font.UNDEFINED, 18, Font.BOLD); Paragraph paragraph = new Paragraph(exportOptions.getHeadline(), titleFont); paragraph.setAlignment(Element.ALIGN_CENTER); document.add(paragraph); document.add(new Paragraph(" ")); document.add(new Paragraph(" ")); } PdfPTable pdftable = pdfExport(table); document.add(pdftable); document.newPage(); document.close(); baos.writeTo(out); out.flush(); baos.close(); } catch (DocumentException e) { logger.error("Error creating document!", e); throw new RuntimeException(e); } catch (IOException e) { logger.error("Error creating document!", e); throw new RuntimeException(e); } finally { } }
From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java
License:Open Source License
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx) throws DocumentException { logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); // added by vic, hsfo Enumeration<String> em = req.getParameterNames(); while (em.hasMoreElements()) { logger.debug("para=" + em.nextElement()); }//from w w w . ja v a 2 s . c om em = req.getAttributeNames(); while (em.hasMoreElements()) logger.debug("attr: " + em.nextElement()); if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) { return generateHsfoRxPDF(req); } String newline = System.getProperty("line.separator"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null; String method = req.getParameter("__method"); String origPrintDate = null; String numPrint = null; if (method != null && method.equalsIgnoreCase("rePrint")) { origPrintDate = req.getParameter("origPrintDate"); numPrint = req.getParameter("numPrints"); } logger.debug("method in generatePDFDocumentBytes " + method); String clinicName; String clinicTel; String clinicFax; // check if satellite clinic is used String useSatelliteClinic = req.getParameter("useSC"); logger.debug(useSatelliteClinic); if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) { String scAddress = req.getParameter("scAddress"); logger.debug("clinic detail" + "=" + scAddress); HashMap<String, String> hm = parseSCAddress(scAddress); clinicName = hm.get("clinicName"); clinicTel = hm.get("clinicTel"); clinicFax = hm.get("clinicFax"); } else { // parameters need to be passed to header and footer clinicName = req.getParameter("clinicName"); logger.debug("clinicName" + "=" + clinicName); clinicTel = req.getParameter("clinicPhone"); clinicFax = req.getParameter("clinicFax"); } String patientPhone = req.getParameter("patientPhone"); String patientCityPostal = req.getParameter("patientCityPostal"); String patientAddress = req.getParameter("patientAddress"); String patientName = req.getParameter("patientName"); String sigDoctorName = req.getParameter("sigDoctorName"); String rxDate = req.getParameter("rxDate"); String rx = req.getParameter("rx"); String patientDOB = req.getParameter("patientDOB"); String showPatientDOB = req.getParameter("showPatientDOB"); String imgFile = req.getParameter("imgFile"); String patientHIN = req.getParameter("patientHIN"); String patientChartNo = req.getParameter("patientChartNo"); String pracNo = req.getParameter("pracNo"); Locale locale = req.getLocale(); boolean isShowDemoDOB = false; if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) { isShowDemoDOB = true; } if (!isShowDemoDOB) patientDOB = ""; if (rx == null) { rx = ""; } String additNotes = req.getParameter("additNotes"); String[] rxA = rx.split(newline); List<String> listRx = new ArrayList<String>(); String listElem = ""; // parse rx and put into a list of rx; for (String s : rxA) { if (s.equals("") || s.equals(newline) || s.length() == 1) { listRx.add(listElem); listElem = ""; } else { listElem = listElem + s; listElem += newline; } } // get the print prop values Properties props = new Properties(); StringBuilder temp = new StringBuilder(); for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getParameter(temp.toString())); } for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString()); } Document document = new Document(); try { String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown"; // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages // however the same graphic will be applied to all pages // ie. __graphicPage=2&__graphicPage=3 String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile"); int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length; if (cfgGraphicFile != null) { // for (String s : cfgGraphicFile) { // p("cfgGraphicFile", s); // } } String[] graphicPage = req.getParameterValues("__graphicPage"); ArrayList<String> graphicPageArray = new ArrayList<String>(); if (graphicPage != null) { // for (String s : graphicPage) { // p("graphicPage", s); // } graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage)); } // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE // the following shows a temp way to get a print page size Rectangle pageSize = PageSize.LETTER; String pageSizeParameter = req.getParameter("rxPageSize"); if (pageSizeParameter != null) { if ("PageSize.HALFLETTER".equals(pageSizeParameter)) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(pageSizeParameter)) { pageSize = PageSize.A6; } else if ("PageSize.A4".equals(pageSizeParameter)) { pageSize = PageSize.A4; } } /* * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; } */ // p("size of page ", props.getProperty(PAGESIZE)); document.setPageSize(pageSize); // 285=left margin+width of box, 5f is space for looking nice document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom writer = PdfWriter.getInstance(document, baosPDF); writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal, patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint, imgFile, patientHIN, patientChartNo, pracNo, locale)); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); document.open(); document.newPage(); PdfContentByte cb = writer.getDirectContent(); BaseFont bf; // = normFont; cb.setRGBColorStroke(0, 0, 255); // render prescriptions for (String rxStr : listRx) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(5f); document.add(p); } // render additional notes if (additNotes != null && !additNotes.equals("")) { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(10f); document.add(p); } // render optometristEyeParam if (req.getAttribute("optometristEyeParam") != null) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph( new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(15f); document.add(p); } // render QrCode if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) { Integer scriptId = Integer.parseInt(req.getParameter("scriptId")); byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId); Image qrCode = Image.getInstance(qrCodeImage); document.add(qrCode); } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } catch (Exception e) { logger.error("Error", e); } finally { if (document != null) { document.close(); } if (writer != null) { writer.close(); } } logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); return baosPDF; }
From source file:questions.separators.TabbedWords1.java
public static void main(String[] args) { Document document = new Document(); try {/*from w w w. j ava 2 s.c o m*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT)); document.open(); Paragraph p; Chunk tab1 = new Chunk(new VerticalPositionMark(), 100); Chunk tab2 = new Chunk(new LineSeparator(), 120); Chunk tab3 = new Chunk(new DottedLineSeparator(), 200); Chunk tab4 = new Chunk(new VerticalPositionMark(), 250); Chunk tab5 = new Chunk(new VerticalPositionMark(), 300); PdfContentByte canvas = writer.getDirectContent(); ColumnText column = new ColumnText(canvas); for (int i = 0; i < 40; i++) { p = new Paragraph("TEST"); p.add(tab1); p.add(new Chunk(String.valueOf(i))); p.add(tab2); p.add(new Chunk(String.valueOf(i * 2))); p.add(tab3); p.add(new Chunk(SeparatedWords2.WORDS[39 - i])); p.add(tab4); p.add(new Chunk(String.valueOf(i * 4))); p.add(tab5); p.add(new Chunk(SeparatedWords2.WORDS[i])); column.addElement(p); } column.setSimpleColumn(60, 36, 400, 806); canvas.moveTo(60, 36); canvas.lineTo(60, 806); canvas.moveTo(160, 36); canvas.lineTo(160, 806); canvas.moveTo(180, 36); canvas.lineTo(180, 806); canvas.moveTo(260, 36); canvas.lineTo(260, 806); canvas.moveTo(310, 36); canvas.lineTo(310, 806); canvas.moveTo(360, 36); canvas.lineTo(360, 806); canvas.moveTo(400, 36); canvas.lineTo(400, 806); canvas.stroke(); column.go(); document.setMargins(60, 195, 36, 36); document.newPage(); for (int i = 0; i < 40; i++) { p = new Paragraph("TEST"); p.add(tab1); p.add(new Chunk(String.valueOf(i))); p.add(tab2); p.add(new Chunk(String.valueOf(i * 2))); p.add(tab3); p.add(new Chunk(SeparatedWords2.WORDS[39 - i])); p.add(tab4); p.add(new Chunk(String.valueOf(i * 4))); p.add(tab5); p.add(new Chunk(SeparatedWords2.WORDS[i])); document.add(p); } document.close(); } catch (Exception de) { de.printStackTrace(); } }
From source file:questions.separators.TabbedWords2.java
public static void main(String[] args) { Document document = new Document(); try {/* w ww. ja va2 s.c o m*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT)); document.open(); Paragraph p; Chunk tab1 = new Chunk(new VerticalPositionMark(), 100, true); Chunk tab2 = new Chunk(new LineSeparator(), 120, true); Chunk tab3 = new Chunk(new DottedLineSeparator(), 200, true); Chunk tab4 = new Chunk(new VerticalPositionMark(), 240, true); Chunk tab5 = new Chunk(new VerticalPositionMark(), 300, true); PdfContentByte canvas = writer.getDirectContent(); ColumnText column = new ColumnText(canvas); for (int i = 0; i < 40; i++) { p = new Paragraph("TEST"); p.add(tab1); p.add(new Chunk(String.valueOf(i))); p.add(tab2); p.add(new Chunk(String.valueOf(i * 2))); p.add(tab3); p.add(new Chunk(SeparatedWords2.WORDS[39 - i])); p.add(tab4); p.add(new Chunk(String.valueOf(i * 4))); p.add(tab5); p.add(new Chunk(SeparatedWords2.WORDS[i])); column.addElement(p); } column.setSimpleColumn(60, 36, 400, 806); canvas.moveTo(60, 36); canvas.lineTo(60, 806); canvas.moveTo(160, 36); canvas.lineTo(160, 806); canvas.moveTo(180, 36); canvas.lineTo(180, 806); canvas.moveTo(260, 36); canvas.lineTo(260, 806); canvas.moveTo(300, 36); canvas.lineTo(300, 806); canvas.moveTo(360, 36); canvas.lineTo(360, 806); canvas.moveTo(400, 36); canvas.lineTo(400, 806); canvas.stroke(); column.go(); document.setMargins(60, 195, 36, 36); document.newPage(); canvas.moveTo(document.left(), document.bottom()); canvas.lineTo(document.left(), document.top()); canvas.moveTo(document.right(), document.bottom()); canvas.lineTo(document.right(), document.top()); canvas.stroke(); for (int i = 0; i < 40; i++) { p = new Paragraph("TEST"); p.add(tab1); p.add(new Chunk(String.valueOf(i))); p.add(tab2); p.add(new Chunk(String.valueOf(i * 2))); p.add(tab3); p.add(new Chunk(SeparatedWords2.WORDS[39 - i])); p.add(tab4); p.add(new Chunk(String.valueOf(i * 4))); p.add(tab5); p.add(new Chunk(SeparatedWords2.WORDS[i])); document.add(p); } document.close(); } catch (Exception de) { de.printStackTrace(); } }
From source file:util.PDFconverter.java
public static void createPDF(String[] header, String[][] data, String path, String tittle, float[] columnWidths) { try {//from w w w . j a v a 2s . co m Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream(path)); doc.open(); doc.setPageSize(PageSize.A4); doc.setMargins(10, 10, 10, 10); Font litle = new Font(Font.COURIER, 7, Font.NORMAL); Font norm = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL); Font normBold = new Font(Font.TIMES_ROMAN, 8, Font.BOLD); Font TitleFont = new Font(Font.TIMES_ROMAN, 12, Font.BOLD); doc.add(Chunk.NEWLINE); Paragraph judul = new Paragraph(tittle, TitleFont); judul.setAlignment(Element.ALIGN_CENTER); doc.add(judul); // Paragraph tgl = new Paragraph("tanggal " + tanggal + "\n", TitleFont); // tgl.setAlignment(Element.ALIGN_CENTER); // doc.add(tgl); doc.add(Chunk.NEWLINE); PdfPTable table = new PdfPTable(header.length); table.setWidthPercentage(100f); for (String head : header) { table.addCell(new PdfPCell(new Phrase(head, normBold))); } for (String[] obj : data) { for (int i = 0; i < header.length; i++) { table.addCell(new PdfPCell(new Phrase(obj[i], norm))); } } //float[] columnWidths = new float[] {10f, 20f, 30f, 10f}; table.setWidths(columnWidths); doc.add(table); // Paragraph stamp = new Paragraph(new Chunk("this report has generated with QCMS by " + System.getProperty("user.name") + " on " + new Date(), litle)); // stamp.setAlignment(Element.ALIGN_BOTTOM); // stamp.setAlignment(Element.ALIGN_CENTER); // doc.add(stamp); // // Paragraph tanda = new Paragraph(new Chunk("Mengetahui,", norm)); // tanda.setSpacingBefore(100); // tanda.setAlignment(Element.ALIGN_RIGHT); // tanda.setAlignment(Element.ALIGN_BOTTOM); // doc.add(tanda); // // Paragraph nama = new Paragraph(new Chunk("MANAGER Dept.RnQ", norm)); // nama.setSpacingBefore(30); // nama.setAlignment(Element.ALIGN_RIGHT); // nama.setAlignment(Element.ALIGN_BOTTOM); // doc.add(nama); doc.close(); } catch (DocumentException | FileNotFoundException ex) { Logger.getLogger(PDFconverter.class.getName()).log(Level.SEVERE, null, ex); } }