List of usage examples for com.lowagie.text Document newPage
public boolean newPage()
From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java
License:Open Source License
@Override public boolean performFinish() { //create the document Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize()); Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); //rotate if we need landscape Document document = new Document(pageSize); try {/*from www .jav a 2 s . c o m*/ //Basic setup of the Document, and get instance of the iText Graphics2D // to pass along to uDig's standard "printing" code. String outputFile = page1.getDestinationDir() + System.getProperty("file.separator") + //$NON-NLS-1$ page1.getOutputFile(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); Graphics2D graphics = null; Template template = getTemplate(); int i = 0; int numPages = 1; do { //sets the active page template.setActivePage(i); PdfContentByte cb = writer.getDirectContent(); Page page = makePage(pageSize, document, template); graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight()); //instantiate a PrinterEngine (pass in the Page instance) PrintingEngine engine = new PrintingEngine(page); //make page format PageFormat pageFormat = new PageFormat(); pageFormat.setOrientation(PageFormat.PORTRAIT); java.awt.print.Paper awtPaper = new java.awt.print.Paper(); awtPaper.setSize(pageSize.getWidth() * 3, pageSize.getHeight() * 3); awtPaper.setImageableArea(0, 0, pageSize.getWidth(), pageSize.getHeight()); pageFormat.setPaper(awtPaper); //run PrinterEngine's print function engine.print(graphics, pageFormat, 0); graphics.dispose(); document.newPage(); if (i == 0) { numPages = template.getNumPages(); } i++; } while (i < numPages); //cleanup document.close(); writer.close(); } catch (DocumentException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (PrinterException e) { e.printStackTrace(); } return true; }
From source file:org.mapfish.print.config.layout.Page.java
License:Open Source License
public void render(PJsonObject params, RenderingContext context) throws DocumentException { final Document doc = context.getDocument(); doc.setPageSize(getPageSizeRect(context, params)); doc.setMargins(getMarginLeft(context, params), getMarginRight(context, params), getMarginTop(context, params) + (header != null ? header.getHeight() : 0), getMarginBottom(context, params) + (footer != null ? footer.getHeight() : 0)); context.getCustomBlocks().setBackgroundPdf(PDFUtils.evalString(context, params, backgroundPdf)); if (doc.isOpen()) { doc.newPage(); } else {//from w ww .j a va 2 s . c o m doc.open(); } context.getCustomBlocks().setHeader(header, params); context.getCustomBlocks().setFooter(footer, params); for (int i = 0; i < items.size(); i++) { Block block = items.get(i); if (block.isVisible(context, params)) { block.render(params, new Block.PdfElement() { public void add(Element element) throws DocumentException { doc.add(element); } }, context); } } }
From source file:org.nabucco.framework.template.impl.service.pdf.util.MergePdfUtil.java
License:Open Source License
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) { Document document = new Document(); try {//from ww w.j av a 2s . c o m List<InputStream> pdfs = streamOfPDFFiles; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
From source file:org.nuxeo.dam.pdf.export.PDFCreator.java
License:Open Source License
public boolean createPDF(String title, OutputStream out) throws ClientException { try {//from w ww . j a v a2 s . c o m Document document = new Document(); PdfWriter.getInstance(document, out); document.addTitle(title); document.addAuthor(Functions.principalFullName(currentUser)); document.addCreator(Functions.principalFullName(currentUser)); document.open(); document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n")); Font titleFont = new Font(Font.HELVETICA, 36, Font.BOLD); Paragraph titleParagraph = new Paragraph(title, titleFont); titleParagraph.setAlignment(Element.ALIGN_CENTER); document.add(titleParagraph); Font authorFont = new Font(Font.HELVETICA, 20); Paragraph authorParagraph = new Paragraph("By " + Functions.principalFullName(currentUser), authorFont); authorParagraph.setAlignment(Element.ALIGN_CENTER); document.add(authorParagraph); document.newPage(); boolean foundOnePicture = false; for (DocumentModel doc : docs) { if (!doc.hasSchema(PICTURE_SCHEMA)) { continue; } foundOnePicture = true; PictureResourceAdapter picture = doc.getAdapter(PictureResourceAdapter.class); Blob blob = picture.getPictureFromTitle(ORIGINAL_JPEG_VIEW); Rectangle pageSize = document.getPageSize(); if (blob != null) { Paragraph imageTitle = new Paragraph(doc.getTitle(), font); imageTitle.setAlignment(Paragraph.ALIGN_CENTER); document.add(imageTitle); Image image = Image.getInstance(blob.getByteArray()); image.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight() - 100); image.setAlignment(Image.MIDDLE); Paragraph imageParagraph = new Paragraph(); imageParagraph.add(image); imageParagraph.setAlignment(Paragraph.ALIGN_MIDDLE); document.add(imageParagraph); document.newPage(); } } if (foundOnePicture) { document.close(); return true; } } catch (Exception e) { throw ClientException.wrap(e); } return false; }
From source file:org.openconcerto.erp.generationDoc.SheetUtils.java
License:Open Source License
public static void convert2PDF(final OpenDocument doc, final File pdfFileToCreate) throws Exception { assert (!SwingUtilities.isEventDispatchThread()); // Open the PDF document Document document = new Document(PageSize.A4, 50, 50, 50, 50); try {//from w ww . ja v a 2 s. c o m FileOutputStream fileOutputStream = new FileOutputStream(pdfFileToCreate); // Create the writer PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream); writer.setPdfVersion(PdfWriter.VERSION_1_6); writer.setFullCompression(); document.open(); PdfContentByte cb = writer.getDirectContent(); // Configure the renderer ODTRenderer renderer = new ODTRenderer(doc); renderer.setIgnoreMargins(false); renderer.setPaintMaxResolution(true); // Scale the renderer to fit width renderer.setResizeFactor(renderer.getPrintWidth() / document.getPageSize().getWidth()); // Print pages for (int i = 0; i < renderer.getPrintedPagesNumber(); i++) { Graphics2D g2 = cb.createGraphics(PageSize.A4.getWidth(), PageSize.A4.getHeight()); // If you want to prevent copy/paste, you can use // g2 = tp.createGraphicsShapes(w, h, true, 0.9f); // Render renderer.setCurrentPage(i); renderer.paintComponent(g2); g2.dispose(); // Add our spreadsheet in the middle of the page if (i < renderer.getPrintedPagesNumber() - 1) document.newPage(); } // Close the PDF document document.close(); // writer.close(); fileOutputStream.close(); } catch (Exception originalExn) { ExceptionHandler.handle("Impossible de crer le PDF " + pdfFileToCreate.getAbsolutePath(), originalExn); } }
From source file:org.openconcerto.erp.graph.GraphSamplePDF.java
License:Open Source License
/** * @param args//www . j av a 2s .c om * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws DocumentException, IOException { // ChartPanel panel = new ChartPanel(c); FileOutputStream baos = new FileOutputStream(new File("OpenConcerto_Chart.pdf")); Document document = new Document(PageSize.A4); // PdfWriter writer = new PdfWriter(document, baos); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte cb = writer.getDirectContent(); System.out.println(document.getPageSize()); createPage1(document, cb); document.newPage(); createPage2(document, cb); document.close(); baos.close(); }
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;//from w w w . j a v a 2 s. co 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.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfDocumentWriter.java
License:Open Source License
public void processPhysicalPage(final PageGrid pageGrid, final LogicalPageBox logicalPage, final int row, final int col, final PhysicalPageKey pageKey) throws DocumentException { final PhysicalPageBox page = pageGrid.getPage(row, col); if (page == null) { return;//from w w w . j av a 2 s . co m } final float width = (float) StrictGeomUtility.toExternalValue(page.getWidth()); final float height = (float) StrictGeomUtility.toExternalValue(page.getHeight()); final Rectangle pageSize = new Rectangle(width, height); final float marginLeft = (float) StrictGeomUtility.toExternalValue(page.getImageableX()); final float marginRight = (float) StrictGeomUtility .toExternalValue(page.getWidth() - page.getImageableWidth() - page.getImageableX()); final float marginTop = (float) StrictGeomUtility.toExternalValue(page.getImageableY()); final float marginBottom = (float) StrictGeomUtility .toExternalValue(page.getHeight() - page.getImageableHeight() - page.getImageableY()); final Document document = getDocument(); document.setPageSize(pageSize); document.setMargins(marginLeft, marginRight, marginTop, marginBottom); if (awaitOpenDocument) { document.open(); awaitOpenDocument = false; } final PdfContentByte directContent = writer.getDirectContent(); final Graphics2D graphics = new PdfGraphics2D(directContent, width, height, metaData); final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable(logicalPage, page); final PhysicalPageDrawable drawable = createPhysicalPageDrawable(logicalPageDrawable, page); drawable.draw(graphics, new Rectangle2D.Double(0, 0, width, height)); graphics.dispose(); document.newPage(); }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfDocumentWriter.java
License:Open Source License
public void processLogicalPage(final LogicalPageKey key, final LogicalPageBox logicalPage) throws DocumentException { final float width = (float) StrictGeomUtility.toExternalValue(logicalPage.getPageWidth()); final float height = (float) StrictGeomUtility.toExternalValue(logicalPage.getPageHeight()); final Rectangle pageSize = new Rectangle(width, height); final Document document = getDocument(); document.setPageSize(pageSize);// w w w .ja v a 2s . c o m document.setMargins(0, 0, 0, 0); if (awaitOpenDocument) { document.open(); awaitOpenDocument = false; } final Graphics2D graphics = new PdfGraphics2D(writer.getDirectContent(), width, height, metaData); // and now process the box .. final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable(logicalPage, null); logicalPageDrawable.draw(graphics, new Rectangle2D.Double(0, 0, width, height)); graphics.dispose(); document.newPage(); }
From source file:org.projectlibre.export.ImageExport.java
License:Common Public License
public static void export(final GraphPageable pageable, Component parentComponent) throws IOException { final File file = chooseFile(pageable.getRenderer().getProject().getName(), parentComponent); final JobQueue jobQueue = SessionFactory.getInstance().getJobQueue(); Job job = new Job(jobQueue, "Image Export", "Exporting Image...", true, parentComponent); job.addRunnable(new JobRunnable("Image Export", 1.0f) { public Object run() throws Exception { boolean pdf = true; if (file.getName().endsWith(".png")) pdf = false;//from ww w. j a v a 2 s .co m Document document = null; PdfWriter writer = null; if (pdf) { document = new Document(); writer = PdfWriter.getInstance(document, new FileOutputStream(file)); } else { } pageable.update(); int pageCount = pageable.getNumberOfPages(); if (pageCount > 0) { ViewPrintable printable = pageable.getSafePrintable(); ExtendedPageFormat pageFormat = pageable.getSafePageFormat(); double width = pageFormat.getWidth(); double height = pageFormat.getHeight(); float startIncrement = 0.1f; float endIncrement = 0.0f; float progressIncrement = (1.0f - startIncrement - endIncrement) / pageCount; for (int p = 0; p < pageCount; p++) { setProgress(startIncrement + p * progressIncrement); if (pdf) { document.setPageSize(new Rectangle((float) width, (float) height)); if (p == 0) document.open(); else document.newPage(); Graphics2D g = writer.getDirectContent().createGraphics((float) width, (float) height); printable.print(g, p); g.dispose(); } else { BufferedImage bi = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D) bi.createGraphics(); g2.setBackground(Color.WHITE); printable.print(g2, p); g2.dispose(); ImageIO.write(bi, "png", new FileOutputStream(file)); break; } } if (pdf) document.close(); } setProgress(1.0f); return null; } }); jobQueue.schedule(job); }