List of usage examples for com.lowagie.text PageSize A4
Rectangle A4
To view the source code for com.lowagie.text PageSize A4.
Click Source Link
From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java
License:Open Source License
@Override public void printResults(List<SudokuData> sudokus, String fileName) throws DocumentException, FileNotFoundException { Document document = new Document(PageSize.A4, 10, 10, 10, 10); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); writeDocument(document, sudokus);//from ww w.j a va2 s . co m writer.close(); }
From source file:de.krutisch.jan.rasterizer.Rasterizer.java
License:Open Source License
public Rasterizer(String[] args) { System.out.println("Rasterizer " + VERSION + "(c) JanKrutisch"); // parse options using getOpt pageSize = PageSize.A4; if (parseOptions(args) == false) return;/* w w w .j a va2 s .c o m*/ // get Time for performance measurement long startTime = new Date().getTime(); CliLogger logger = new CliLogger(); if (verbose) logger.setLogLevel(EventLogger.VERBOSE); RasterizerImage ri = RasterizerImage.getInstance(logger); RasterizerPdf rp = RasterizerPdf.getInstance(logger); if (!ri.loadImageFromFile(inputFilename)) { System.out.println("Image file '" + inputFilename + "' couldn't be opened. aborting."); return; } rp.setOutputFile(outputFilename); if (printColor) { rp.setColorMode(RasterizerPdf.SIMPLECOLOR); } rp.setPageSize(pageSize); rp.setDotSize(dotSize); rp.setMargins(36, 36, 36, 36); rp.setLandscape(landscape); if (printAllCropmarks) { rp.setCropmarks(RasterizerPdf.ALLCROPMARKS); } else if (printCropmarks) rp.setCropmarks(RasterizerPdf.CROPMARKS); rp.setHorizontalPages(xPages); RasterThread rt = new RasterThread(ri, rp, logger); rt.start(); logger.log(EventLogger.VERBOSE, "detached"); long fullTime = new Date().getTime() - startTime; }
From source file:de.krutisch.jan.rasterizer.Rasterizer.java
License:Open Source License
private void setPageSize(String p) { if ("A4".equals(p)) { pageSize = PageSize.A4; } else if ("A3".equals(p)) { pageSize = PageSize.A3;//from ww w . j a va 2 s.co m } else if ("LETTER".equals(p)) { pageSize = PageSize.LETTER; } else if ("LEGAL".equals(p)) { pageSize = PageSize.LEGAL; } if (pageSize == null) pageSize = PageSize.A4; }
From source file:de.maklerpoint.office.Schnittstellen.PDF.ExportListePDF.java
License:Open Source License
public void write() throws DocumentException, FileNotFoundException { SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm"); Document doc = null;//from ww w.j av a 2 s. co m if (titles.length > 7) doc = new Document(PageSize.A4.rotate(), 20, 20, 20, 20); else doc = new Document(PageSize.A4, 20, 20, 20, 20); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename)); doc.addAuthor("MaklerPoint - www.maklerpoint.de"); doc.addCreator("MaklerPoint - www.maklerpoint.de"); doc.addCreationDate(); doc.addTitle(title); doc.open(); doc.add(new Paragraph(title, FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, Color.BLACK))); Table t = new Table(titles.length, data.length + 1); t.setPadding(3); t.setSpacing(0); t.setBorderWidth(1); for (int i = 0; i < titles.length; i++) { Cell c1 = new Cell(titles[i]); c1.setHeader(true); t.addCell(c1); } t.endHeaders(); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { Cell c1 = null; if (data[i][j] != null) c1 = new Cell(data[i][j].toString()); else c1 = new Cell(""); t.addCell(c1); } } doc.add(t); if (footer == null) { doc.add(new Paragraph( ("Export " + title + " - Genereriert am " + df.format(new Date(System.currentTimeMillis()))) + " von MaklerPoint", FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black))); } else { doc.add(new Paragraph(footer, FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black))); } doc.close(); }
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 www . 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
/****************************************************************************************************** * Adds the all pages.//from w w w . j a v a2 s . c o m * * @param pagesizemode {@link PdfPageSize} * @param writer {@link PdfWriter} * @param pdfdoc {@link Document} * @return {@link PdfPageLabels} * * * @throws ImageInterpreterException the image interpreter exception * @throws IOException Signals that an I/O exception has occurred. * @throws MalformedURLException the malformed url exception * @throws PDFManagerException the PDF manager exception * @throws ImageManagerException *******************************************************************************************************/ private PdfPageLabels addAllPages(PdfPageSize pagesizemode, PdfWriter writer, Document pdfdoc, Watermark myWatermark) throws ImageInterpreterException, IOException, MalformedURLException, PDFManagerException, ImageManagerException { PdfPageLabels pagelabels = new PdfPageLabels(); int pageadded = 0; // sort the HashMap by the KeySet (pagenumber) Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs); float scalefactor = 1; // scaling factor of the image int page_w = PaperSize.A4.width; int page_h = PaperSize.A4.height; LOGGER.debug("iterate over " + imageURLs.size() + " pages."); for (Integer imageKey : sortedMap.keySet()) { Watermark watermark = myWatermark; Image pdfImage = null; // PDF-Image LOGGER.debug("Writing page " + imageKey); boolean errorPage = false; // true if the image does not exists URL errorUrl = null; // url of the image that does not exists // ------------------------------------------------------------------------------------------------ // Title page available. Render it in pdftitlepage // ------------------------------------------------------------------------------------------------ if ((pdftitlepages != null) && (pdftitlepages.get(imageKey) != null)) { // title page PDFTitlePage pdftitlepage = pdftitlepages.get(imageKey); // create new PDF page try { pdfdoc.setPageSize(PageSize.A4); pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(), pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin()); pageadded++; pdfdoc.newPage(); // create new page // set page name pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "-"); } catch (Exception e1) { throw new PDFManagerException("PDFManagerException occured while creating new page in PDF", e1); } // render title page pdftitlepage.render(pdfdoc); } // ------------------------------------------------------------------------------------------------ // Process image with imageKey // ------------------------------------------------------------------------------------------------ UrlImage pdfpage = imageURLs.get(imageKey); if (pdfpage.getURL() != null) { boolean added = false; boolean scaled = false; URL url = pdfpage.getURL(); // pdf hack if (ContentServerConfiguration.getInstance().getUsePdf()) { LOGGER.debug("trying to find original pdf"); PdfContentByte pdfcb = null; PdfReader pdfreader = null; PdfImportedPage importpage = null; try { String pdfpath = ContentServerConfiguration.getInstance().getRepositoryPathPdf() .replace("file:///", ""); LOGGER.debug("looking in " + pdfpath + " for pdf file"); String tiffPath = ContentServerConfiguration.getInstance().getRepositoryPathImages() .replace("file:///", ""); // String urlString = url.toString(); int pageNumber = pdfpage.getPageNumber(); // UrlImage copy = new PDFPage(pdfpage); URL pdfurl = new URL(url.toString().replace(tiffPath, pdfpath) .replace(url.toString().substring(url.toString().lastIndexOf(".")), ".pdf")); LOGGER.debug("pdfurl = " + pdfurl); if (new File(pdfurl.toURI()).exists()) { LOGGER.debug("found pdf " + pdfurl.toURI()); // copy.setURL(pdfurl); pdfcb = writer.getDirectContent(); pdfreader = new PdfReader(pdfurl); importpage = writer.getImportedPage(pdfreader, pageNumber); LOGGER.debug("creating orig pdf page"); Rectangle rect = pdfreader.getPageSize(pageNumber); try { pdfdoc.setPageSize(rect); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } pageadded++; pdfcb.addTemplate(importpage, 0, 0); added = true; LOGGER.debug("page:" + imageKey + " url: " + pdfurl.toString()); } } catch (URISyntaxException e) { LOGGER.debug(e); added = false; } finally { if (writer != null) { writer.freeReader(pdfreader); writer.flush(); } if (pdfreader != null) { pdfreader.close(); } } } if (!added) { // image file LOGGER.debug("using image to create pdf page"); // try to get ImageInterpreter from url ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost, httpproxyport, httpproxyuser, httpproxypassword); try { // check preferred compression type depending on color depth Embedd preferredEmbeddingType = Embedd.ORIGBYTESTREAM; if (myInterpreter.getColordepth() == 1) { // bitonal image preferredEmbeddingType = embeddBitonalImage; } else if ((myInterpreter.getColordepth() > 1) && (myInterpreter.getSamplesperpixel() == 1)) { // greyscale image preferredEmbeddingType = embeddGreyscaleImage; } else { // color image preferredEmbeddingType = embeddColorImage; } // ------------------------------------------------------------------------------------- // Try to generate image // ------------------------------------------------------------------------------------- pdfImage = generatePdfImageFromInterpreter(myInterpreter, preferredEmbeddingType, errorPage, watermark, errorUrl); // ------------------------------------------------------------------------------------- // image couldn't be embedded yet (emergencyCase) // ------------------------------------------------------------------------------------- if (pdfImage == null) { LOGGER.warn( "Couldn't use preferred method for embedding the image. Instead had to use JPEG or RenderedImage"); // Get Interpreter and rendered Image // --------------------------------------------------------------------------------------------------------------------------------- RenderedImage ri = null; if (preferredEmbeddingType == embeddBitonalImage) { ImageManager sourcemanager = new ImageManager(url); boolean watermarkscale = ContentServerConfiguration.getInstance() .getScaleWatermark(); // should we scale // the watermark ? ri = sourcemanager.scaleImageByPixel(3000, 0, ImageManager.SCALE_BY_WIDTH, 0, null, null, watermark, watermarkscale, ImageManager.BOTTOM); myInterpreter = sourcemanager.getMyInterpreter(); } else { ri = myInterpreter.getRenderedImage(); if (watermark != null) { ri = addwatermark(ri, watermark, 2); myInterpreter.setHeight( myInterpreter.getHeight() + watermark.getRenderedImage().getHeight()); } } // scale rendered image // --------------------------------------------------------------------------------------------------------------------------------- // float scalefactorX = 1; // float scalefactorY = 1; // switch (pagesizemode) { // case ORIGINAL: // scalefactorX = 72f / myInterpreter.getXResolution(); // scalefactorY = 72f / myInterpreter.getYResolution(); // break; // default: // /* // * check, if the image needs to be scaled, because // * it's bigger than A4 calculate the new scalefactor // */ // float page_w_pixel = (float) (page_w * // myInterpreter.getXResolution() / 25.4); // float page_h_pixel = (float) (page_h * // myInterpreter.getYResolution() / 25.4); // // float res_x = myInterpreter.getXResolution(); // float res_y = myInterpreter.getYResolution(); // // long w = myInterpreter.getWidth(); // get height and // // width // long h = myInterpreter.getHeight(); // // if ((w > page_w_pixel) || (h > page_h_pixel)) { // LOGGER.debug("scale image to fit the page"); // float scalefactor_w = page_w_pixel / w; // float scalefactor_h = page_h_pixel / h; // if (scalefactor_h < scalefactor_w) { // scalefactor = scalefactor_h; // } else { // scalefactor = scalefactor_w; // } // w = (long) (w * scalefactor); // h = (long) (h * scalefactor); // } // scalefactorX = (72f / res_x) * scalefactor; // scalefactorY = (72f / res_y) * scalefactor; // break; // } // //scalefactorX = 0.2f; // //scalefactorY = 0.2f; // if (preferredEmbeddingType == embeddBitonalImage) { // ImageManager sourcemanager = new ImageManager(url); // ri = sourcemanager.scaleImageByPixel((int) // (scalefactorX*100), (int) (scalefactorY*100), // ImageManager.SCALE_BY_PERCENT, 0, null, null, // watermark, true, ImageManager.BOTTOM); // }else{ // ri = ImageManipulator.scaleInterpolationBilinear(ri, // scalefactorX, scalefactorY); // } // myInterpreter.setHeight(ri.getHeight()); // myInterpreter.setWidth(ri.getWidth()); // scaled = true; // add Watermark // --------------------------------------------------------------------------------------------------------------------------------- // ri = addwatermark(ri, watermark, // ImageManager.BOTTOM); // myInterpreter.setHeight(myInterpreter.getHeight() + // watermark.getRenderedImage().getHeight()); // Try to write into pdfImage // --------------------------------------------------------------------------------------------------------------------------------- if (myInterpreter.getColordepth() > 1) { // compress image if greyscale or color ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream(); // JpegInterpreter jpint = new JpegInterpreter(ri); // jpint.setXResolution(myInterpreter.getXResolution()); // jpint.setYResolution(myInterpreter.getYResolution()); // jpint.writeToStream(null, bytesoutputstream); LOGGER.error("WritingJPEGImage"); writeJpegFromRenderedImageToStream(bytesoutputstream, ri, null, myInterpreter); byte[] returnbyteArray = bytesoutputstream.toByteArray(); if (bytesoutputstream != null) { bytesoutputstream.flush(); bytesoutputstream.close(); } pdfImage = Image.getInstance(returnbyteArray); returnbyteArray = null; } else { // its bitonal, but can't be embedded directly, // need to go via RenderedImage BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri); pdfImage = Image.getInstance(buffImage, null, false); if (myWatermark != null) { // create Image for Watermark JpegInterpreter jpint = new JpegInterpreter(myWatermark.getRenderedImage()); ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream(); jpint.setXResolution(myInterpreter.getXResolution()); jpint.setYResolution(myInterpreter.getYResolution()); jpint.writeToStream(null, bytesoutputstream); byte[] returnbyteArray = bytesoutputstream.toByteArray(); jpint.clear(); if (bytesoutputstream != null) { bytesoutputstream.flush(); bytesoutputstream.close(); } Image blaImage = Image.getInstance(returnbyteArray); returnbyteArray = null; // set Watermark as Footer at fixed position // (200,200) Chunk c = new Chunk(blaImage, 200, 200); Phrase p = new Phrase(c); HeaderFooter hf = new HeaderFooter(p, false); pdfdoc.setFooter(hf); } // pdfdoc.setPageSize(arg0) // TODO das scheint nicht zu funktionieren... sollte // dieser Code entfernt werden? } } // end of : if (pdfImage == null) { } catch (BadElementException e) { throw new PDFManagerException("Can't create a PDFImage from a Buffered Image.", e); } catch (ImageManipulatorException e) { LOGGER.warn(e); } // --------------------------------------------------------------------------------------------------------- // place the image on the page // --------------------------------------------------------------------------------------------------------- if (pagesizemode == PdfPageSize.ORIGINAL) { // calculate the image width and height in points, create // the rectangle in points Rectangle rect = null; if (!scaled) { float image_w_points = (myInterpreter.getWidth() / myInterpreter.getXResolution()) * 72; float image_h_points = ((myInterpreter.getHeight()) / myInterpreter.getYResolution()) * 72; rect = new Rectangle(image_w_points, image_h_points); } else { rect = new Rectangle(myInterpreter.getWidth(), myInterpreter.getHeight()); } // create the pdf page according to this rectangle LOGGER.debug("creating original page sized PDF page:" + rect.getWidth() + " x " + rect.getHeight()); pdfdoc.setPageSize(rect); // create new page to put the content try { pageadded++; pdfdoc.newPage(); } catch (Exception e1) { throw new PDFManagerException( "DocumentException occured while creating page " + pageadded + " in PDF", e1); } // scale image and place it on page; scaling the image does // not scale the images bytestream if (!scaled) { pdfImage.scalePercent((72f / myInterpreter.getXResolution() * 100), (72f / myInterpreter.getYResolution() * 100)); } pdfImage.setAbsolutePosition(0, 0); // set image to lower // left corner boolean result; try { result = pdfdoc.add(pdfImage); // add it to PDF if (!result) { throw new PDFManagerException("Image \"" + url.toString() + "\" can's be added to PDF! Error during placing image on page"); } } catch (DocumentException e) { throw new PDFManagerException("DocumentException occured while adding the image to PDF", e); } } else { /* * it is not the original page size PDF will contain only A4 pages */ LOGGER.debug("creating A4 pdf page"); // create new page to put the content try { pageadded++; pdfdoc.setPageSize(PageSize.A4); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } float page_w_pixel = (float) (page_w * myInterpreter.getXResolution() / 25.4); float page_h_pixel = (float) (page_h * myInterpreter.getYResolution() / 25.4); float res_x = myInterpreter.getXResolution(); float res_y = myInterpreter.getYResolution(); long w = myInterpreter.getWidth(); // get height and width long h = myInterpreter.getHeight(); /* * if the page is landscape, we have to rotate the page; this is only done in PDF, the orig image bytestream is NOT rotated */ if (w > h) { LOGGER.debug("rotate image"); // must be rotated pdfImage.setRotationDegrees(90); // change width and height long dummy = w; w = h; h = dummy; // change the resolutions x and y float dummy2 = res_x; res_x = res_y; res_y = dummy2; } /* * check, if the image needs to be scaled, because it's bigger than A4 calculate the new scalefactor */ if ((w > page_w_pixel) || (h > page_h_pixel)) { LOGGER.debug("scale image to fit the page"); float scalefactor_w = page_w_pixel / w; float scalefactor_h = page_h_pixel / h; if (scalefactor_h < scalefactor_w) { scalefactor = scalefactor_h; } else { scalefactor = scalefactor_w; } w = (long) (w * scalefactor); h = (long) (h * scalefactor); } if (!scaled) { pdfImage.scalePercent((72f / res_x * 100) * scalefactor, (72f / res_y * 100) * scalefactor); } // center the image on the page // --------------------------------------------------------------- float y_offset = 0; // y - offset // get image size in cm; height float h_cm = (float) (h / (res_x / 2.54)); // float w_cm = (float) (w / (res_y / 2.54)); // and width if ((h_cm + 2) < (page_h / 10)) { y_offset = 2 * 72f / 2.54f; } float freespace_x = ((page_w_pixel - w) / res_x * 72f); float freespace_y = ((page_h_pixel - h) / res_y * 72f) - (y_offset); // set position add image pdfImage.setAbsolutePosition(freespace_x / 2, freespace_y); boolean result; try { result = pdfdoc.add(pdfImage); } catch (DocumentException e) { LOGGER.error(e); throw new PDFManagerException("DocumentException occured while adding the image to PDF", e); } if (!result) { // placing the image in the PDF was not successful throw new PDFManagerException("Image \"" + url.toString() + "\" can's be added to PDF! Error during placing image on page"); } // draw box around the image page // ------------------------------------------------------------------------------------------------ if (pagesizemode == PdfPageSize.A4BOX) { LOGGER.debug("draw box around the image page"); // draw a black frame around the image PdfContentByte pcb = writer.getDirectContent(); // calculate upper left corner of the box (measurment is // in points) float left_x = (freespace_x / 2); float left_y = freespace_y; // calculate the lower right corner of the box // (measurement is in points) float image_w_points = (w / res_x) * 72; float image_h_points = (h / res_y) * 72; pcb.setLineWidth(1f); pcb.stroke(); pcb.rectangle(left_x, left_y, image_w_points, image_h_points); pcb.stroke(); } } // end of: if (pagesizemode == PdfPageSize.ORIGINAL) { pdfImage = null; myInterpreter.clear(); // writer.freeReader(new PdfReader(pdfpage.getURL())); } // end of : if (pdfpage.getURL() != null) { // ------------------------------------------------------------------------------------------------ // it is a page from a PDF file which should be inserted // ------------------------------------------------------------------------------------------------ else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) { PdfContentByte pdfcb = writer.getDirectContent(); PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader(); PdfImportedPage importpage = writer.getImportedPage(pdfreader, pdfpage.getPageNumber()); if (pagesizemode == PdfPageSize.ORIGINAL) { LOGGER.debug("creating orig pdf page"); Rectangle rect = pdfreader.getPageSize(pdfpage.getPageNumber()); try { pdfdoc.setPageSize(rect); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } // add content pageadded++; pdfcb.addTemplate(importpage, 0, 0); } else { LOGGER.debug("creating A4 pdf page"); try { pdfdoc.setPageSize(PageSize.A4); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } // add content pageadded++; pdfcb.addTemplate(importpage, 0, 0); // draw box // if (pagesizemode == PdfPageSize.A4BOX) { // FIXME: nichts implementiert ? // } } } // handle pagename if (imageNames != null) { String pagename = imageNames.get(imageKey); if (pagename != null) { pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, pagename); } else { pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "unnumbered"); } } // handle bookmarks and set destinator for bookmarks LOGGER.debug("handle bookmark(s) for page"); PdfDestination destinator = new PdfDestination(PdfDestination.FIT); setBookmarksForPage(writer, destinator, imageKey); // the key in the writer.flush(); // mashMap is the pagenumber } // end of while iterator over all pages } return pagelabels; }
From source file:de.xirp.report.ReportGenerator.java
License:Open Source License
/** * Generates the PDF from the/*from w w w . jav a 2 s . c o m*/ * {@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:de.xirp.report.ReportGenerator.java
License:Open Source License
/** * Adds a/*from www. ja va 2s.co m*/ * {@link de.xirp.report.data.ContentPart part} to * the PDF {@link com.lowagie.text.Document}. * * @param part * The content part to add. * @param first * The first added item. * @throws MalformedURLException * if something went wrong saving the PDF. * @throws IOException * if something went wrong saving the PDF. * @throws DocumentException * if something went wrong adding the page. * @see de.xirp.report.data.ContentPart * @see de.xirp.report.data.IContentPartItem * @see com.lowagie.text.Document */ private static void addPart(ContentPart part, IContentPartItem first) throws MalformedURLException, IOException, DocumentException { if (first instanceof ContentPartTable) { document.setPageSize(PageSize.A4.rotate()); } document.newPage(); for (IContentPartItem item : part.getItems()) { if (item instanceof ContentPartImage) { logClass.debug("IMAGE part created in report." + Constants.LINE_SEPARATOR); //$NON-NLS-1$ addImage((ContentPartImage) item); addSkip(); } if (item instanceof ContentPartText) { logClass.debug("TEXT part created in report." + Constants.LINE_SEPARATOR); //$NON-NLS-1$ addText((ContentPartText) item); addSkip(); } if (item instanceof ContentPartTable) { logClass.debug("TABLE part created in report." + Constants.LINE_SEPARATOR); //$NON-NLS-1$ if (!first.equals(item)) { document.setPageSize(PageSize.A4.rotate()); document.newPage(); } addTable((ContentPartTable) item); document.setPageSize(PageSize.A4); document.newPage(); } if (item instanceof ContentPartList) { logClass.debug("LIST part created in report." + Constants.LINE_SEPARATOR); //$NON-NLS-1$ addList((ContentPartList) item); addSkip(); } // if (item instanceof ContentPartVideo) { // logClass.debug("VIDEO part created in // report."+Constants.LINE_SEPARATOR); // //$NON-NLS-1$ // addVideo((ContentPartVideo) item); // addSkip( ); // } } logClass.debug("Part finished." + Constants.LINE_SEPARATOR); //$NON-NLS-1$ }
From source file:ec.edu.chyc.manejopersonal.managebean.PDFCustomExporter.java
License:Apache License
@Override public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle, boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor, MethodExpression postProcessor, boolean subTable) throws IOException { try {/*www . j a va 2s . co m*/ Document document = new Document(); if (orientation.equalsIgnoreCase("Landscape")) { document.setPageSize(PageSize.A4.rotate()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); StringTokenizer st = new StringTokenizer(tableId, ","); while (st.hasMoreElements()) { String tableName = (String) st.nextElement(); UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(), tableName); if (component == null) { throw new FacesException("Cannot find component \"" + tableName + "\" in view."); } if (!(component instanceof DataTable || component instanceof DataList)) { throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName() + "\", exporter must target a PrimeFaces DataTable/DataList."); } if (preProcessor != null) { preProcessor.invoke(context.getELContext(), new Object[] { document }); } if (!document.isOpen()) { document.open(); } if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) { Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE, Font.BOLD); Paragraph title = new Paragraph(tableTitle, tableTitleFont); document.add(title); Paragraph preface = new Paragraph(); addEmptyLine(preface, 3); document.add(preface); } PdfPTable pdf; DataList list = null; DataTable table = null; if (component instanceof DataList) { list = (DataList) component; pdf = exportPDFTable(context, list, pageOnly, encodingType); } else { table = (DataTable) component; pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable); } if (pdf != null) { document.add(pdf); } // add a couple of blank lines Paragraph preface = new Paragraph(); addEmptyLine(preface, datasetPadding); document.add(preface); if (postProcessor != null) { postProcessor.invoke(context.getELContext(), new Object[] { document }); } } document.close(); writePDFToResponse(context.getExternalContext(), baos, filename); } catch (DocumentException e) { throw new IOException(e.getMessage()); } }
From source file:edtscol.client.Imprime.java
License:CeCILL license
private void ouvrirDocument() { try {//w w w . j a v a 2 s . co m document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); writer = PdfWriter.getInstance(document, new FileOutputStream(chemin)); initMetaDocument(); document.open(); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } }