List of usage examples for com.lowagie.text.pdf PdfContentByte setLineWidth
public void setLineWidth(float w)
From source file:com.estate.pdf.Page.java
protected void drawSpacingGrid(Rectangle rct, float spacing, Color color) { PdfContentByte cb = writer.getDirectContentUnder(); cb.setLineWidth(.25f); cb.setColorStroke(color);/* w w w .ja v a 2 s. c o m*/ for (float x = 0; x < rct.getRight(); x += spacing) { cb.moveTo(x, 0); cb.lineTo(x, rct.getTop()); } for (float y = 0; y < rct.getTop(); y += spacing) { cb.moveTo(0, y); cb.lineTo(rct.getRight(), y); } cb.stroke(); }
From source file:com.estate.pdf.PageBorder.java
public void draw(Document doc, int iconNum, String pageNum, String toolName) { try {//from www . j a v a 2 s. c o m PdfContentByte cb = writer.getDirectContentUnder(); BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252, BaseFont.EMBEDDED); BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252, BaseFont.EMBEDDED); Rectangle rct = new Rectangle(doc.getPageSize()); float iconBase = (1.25f * 72); // This is the base of the icons on // the page Image icon = Image.getInstance(Locations.getImageLocation() + icons[iconNum]); // Image box = Image.getInstance(Locations.ImageLocation() + // "blueBOX.png"); icon.scalePercent(23); float scale = .23f; float iconLeft = (icon.getWidth() / 2) * scale; float boxSize = (.1875f * 72); // Adjust the top rct.setTop(rct.getTop() - (.5f * 72)); // Place the Icon icon.setAbsolutePosition((1.25f * 72) - iconLeft, rct.getTop() - iconBase); doc.add(icon); // Set our line color cb.setRGBColorStroke(0, 72, 117); cb.setLineWidth(.75f); // do the bottom line cb.moveTo(1.25f * 72, (.5f * 72)); cb.lineTo(rct.getRight() - (.5f * 72), (.5f * 72)); cb.moveTo(1.25f * 72, (.5f * 72)); cb.lineTo(1.25f * 72, rct.getTop()); // stroke the lines cb.stroke(); // Do the lower left box cb.rectangle((1.25f - 0.09375f) * 72, (.5f - 0.09375f) * 72, boxSize, boxSize); cb.setRGBColorFill(0, 72, 117); cb.closePathFillStroke(); // Do the lower right box Rectangle pnRect = new Rectangle(0, 0); pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72)); pnRect.setTop((.5f - 0.09375f) * 72); pnRect.setRight(pnRect.getLeft() + boxSize); pnRect.setBottom(pnRect.getTop() - boxSize); // cb.rectangle(rct.getRight() - ((.5f + 0.09375f) * 72), (.5f - // 0.09375f) * 72, (.1875f * 72), (.1875f * 72)); cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize); cb.setRGBColorFill(0, 72, 117); cb.closePathFillStroke(); // Now we do the page number if one is supplied. if (pageNum.length() > 0) { float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9); float pnWidth = fontBold.getWidthPoint(pageNum, 9); float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2); float b = pnRect.getTop() + ((boxSize - pnHeight) / 2); cb.beginText(); cb.setFontAndSize(fontBold, 9); cb.setRGBColorFill(255, 255, 255); cb.setTextMatrix(l, b); cb.showText(pageNum); cb.endText(); } // Display the copyright SimpleDateFormat df = new SimpleDateFormat("yyyy"); char cs = 0x00a9; // Unicode for the copyright symbol String copyRight = com.estate.constants.StringConstants.copyRight + cs + " " + df.format(new Date()); float crWidth; float crLeft; crWidth = font.getWidthPoint(copyRight, 8); cb.beginText(); cb.setFontAndSize(font, 8); cb.setRGBColorFill(0, 0, 0); crLeft = (doc.getPageSize().getRight() - crWidth) / 2; cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the // copyright at 3/8" up from // the bottom cb.showText(copyRight); cb.endText(); if (toolName.length() > 0) { cb.beginText(); cb.setFontAndSize(font, 8); cb.setRGBColorFill(0, 0, 0); cb.setTextMatrix((1.25f * 72) + boxSize, .375f * 72); cb.showText(toolName); cb.endText(); } // Fix a licensee at left cb.beginText(); cb.setFontAndSize(font, 8); cb.setRGBColorFill(0, 0, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72), .375f * 72, 0); cb.endText(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.qcadoo.report.api.pdf.PdfPageNumbering.java
License:Open Source License
private void buildFooter(final PdfWriter writer, final Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState();/* w ww. ja v a 2 s . co m*/ String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " "; float textBase = document.bottom() - 25; float textSize = FontUtils.getDejavu().getWidthPoint(text, 7); cb.setColorFill(ColorUtils.getLightColor()); cb.setColorStroke(ColorUtils.getLightColor()); cb.setLineWidth(1); cb.setLineDash(2, 2, 1); cb.moveTo(document.left(), document.bottom() - 10); cb.lineTo(document.right(), document.bottom() - 10); cb.stroke(); cb.beginText(); cb.setFontAndSize(FontUtils.getDejavu(), 7); float adjust = FontUtils.getDejavu().getWidthPoint("0", 7); cb.setTextMatrix(document.right() - textSize - adjust, textBase); cb.showText(text); textSize = FontUtils.getDejavu().getWidthPoint(footer.getGeneratedBy(), 7); cb.setTextMatrix(document.right() - textSize, textBase - 10); cb.showText(footer.getGeneratedBy()); textSize = FontUtils.getDejavu().getWidthPoint(generationDate, 7); cb.setTextMatrix(document.right() - textSize, textBase - 20); cb.showText(generationDate); cb.endText(); try { textSize = FontUtils.getDejavu().getWidthPoint(footer.getAdditionalText(), 7); ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(new Phrase(footer.getAdditionalText(), FontUtils.getDejavuRegular7Light()), document.left() + 240, textBase + 10, document.left() + 390, textBase - 25, 10, Element.ALIGN_LEFT); ct.go(); } catch (DocumentException e) { LOG.warn("Problem with additional text generation in report footer."); } try { ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(document.left(), textBase + 10, document.left() + 230, textBase - 25, 10, Element.ALIGN_LEFT); ct.addText(new Phrase(footer.getCompanyName() + "\n", FontUtils.getDejavuRegular7Light())); if (!"".equals(footer.getAddress())) { ct.addText(new Phrase(footer.getAddress() + "\n", FontUtils.getDejavuRegular7Light())); } if (!"".equals(footer.getPhoneEmail())) { ct.addText(new Phrase(footer.getPhoneEmail(), FontUtils.getDejavuRegular7Light())); } ct.go(); } catch (DocumentException e) { LOG.warn("Problem with company text generation in report footer."); } cb.addTemplate(total, document.right() - adjust, textBase); cb.restoreState(); }
From source file:com.qcadoo.report.api.pdf.PdfPageNumbering.java
License:Open Source License
private void buildHeader(final PdfWriter writer, final Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState();//from w ww. ja va2s.c o m String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " "; float textBase = document.top() + 22; float textSize = FontUtils.getDejavu().getWidthPoint(text, 7); cb.setColorFill(ColorUtils.getLightColor()); cb.setColorStroke(ColorUtils.getLightColor()); cb.beginText(); cb.setFontAndSize(FontUtils.getDejavu(), 7); float adjust = FontUtils.getDejavu().getWidthPoint("0", 7); cb.setTextMatrix(document.right() - textSize - adjust, textBase); cb.showText(text); cb.endText(); cb.addTemplate(total, document.right() - adjust, textBase); cb.setLineWidth(1); cb.setLineDash(2, 2, 1); cb.moveTo(document.left(), document.top() + 12); cb.lineTo(document.right(), document.top() + 12); cb.stroke(); cb.restoreState(); }
From source file:com.qcadoo.report.api.pdf.TableBorderEvent.java
License:Open Source License
@Override public void tableLayout(final PdfPTable table, final float[][] widths, final float[] heights, final int headerRows, final int rowStart, final PdfContentByte[] canvases) { float[] width = widths[0]; float x1 = width[0]; float x2 = width[width.length - 1]; float y1 = heights[0]; float y2 = heights[heights.length - 1]; PdfContentByte cb = canvases[PdfPTable.LINECANVAS]; cb.saveState();/*from www .j a va 2 s .com*/ cb.setLineWidth(1); cb.setColorStroke(ColorUtils.getLineDarkColor()); cb.rectangle(x1, y1, x2 - x1, y2 - y1); cb.stroke(); cb.restoreState(); }
From source file:com.t2.compassionMeditation.ViewSessionsActivity.java
License:Open Source License
/** * Create a PDF file based on the contents of the graph */// w w w . j a va 2s .com void CreatePdf() { // Run the export on a separate thread. new Thread(new Runnable() { @Override public void run() { Document document = new Document(); try { Date calendar = Calendar.getInstance().getTime(); mResultsFileName = "BioZenResults_"; mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-" + calendar.getDate() + "_"; mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-" + calendar.getSeconds() + ".pdf"; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + mResultsFileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // Note top of PDF = 900 float chartWidth = 332; float chartHeight = 45; float spaceHeight = chartHeight + 30; int horizontalPos = 180; float verticalPos = 780; // Write document header contentByte.beginText(); contentByte.setFontAndSize(baseFont, 20); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "Generated on: " + calendar.toLocaleString(), 300, 770, 0); contentByte.endText(); contentByte.setLineWidth(1f); verticalPos -= spaceHeight; long startTime = startCal.getTimeInMillis(); long endTime = endCal.getTimeInMillis(); float maxChartValue = 0; float chartYAvg; BioSession tmpSession = sessionItems.get(0); int maxKeys = tmpSession.keyItemNames.length; // Loop through all of the the keys for (int key = 0; key < maxKeys; key++) { //Draw a border rect contentByte.setRGBColorStrokeF(0, 0, 0); contentByte.setLineWidth(1f); contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight); contentByte.stroke(); // Write band name contentByte.beginText(); contentByte.setFontAndSize(baseFont, 12); BioSession tmpSession1 = sessionItems.get(0); contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170, (verticalPos + (chartHeight / 2)) - 5, 0); contentByte.endText(); maxChartValue = 0; // First find the max Y for (BioSession session : sessionItems) { if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; if (chartYAvg > maxChartValue) maxChartValue = chartYAvg; } } float lastY = -1; float xIncrement = 0; if (sessionItems.size() > 0) { xIncrement = chartWidth / sessionItems.size(); } float yIncrement = 0; if (maxChartValue > 0) { yIncrement = chartHeight / maxChartValue; } float highValue = 0; int highTime = 0; float highY = 0; float highX = 0; int lowTime = 0; float lowY = 100; float lowX = chartWidth; float lowValue = maxChartValue; int lCount = 0; String keyName = ""; ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>(); // Loop through the session points of this key String rawYValues = ""; for (BioSession session : sessionItems) { keyName = session.keyItemNames[key]; if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; rawYValues += chartYAvg + ", "; if (lastY < 0) lastY = (float) chartYAvg; contentByte.setLineWidth(3f); contentByte.setRGBColorStrokeF(255, 0, 0); float graphXFrom = horizontalPos + (lCount * xIncrement); float graphYFrom = verticalPos + (lastY * yIncrement); float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement)); float graphYTo = verticalPos + (chartYAvg * yIncrement); // Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]"); // Draw the actual graph contentByte.moveTo(graphXFrom, graphYFrom); contentByte.lineTo(graphXTo, graphYTo); contentByte.stroke(); //Add regression Item ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement))); if (chartYAvg > highValue) { highValue = chartYAvg; highY = graphYTo; highX = graphXTo; highTime = (int) (session.time / 1000); } if (chartYAvg < lowValue) { lowValue = chartYAvg; lowY = graphYTo; lowX = graphXTo; lowTime = (int) (session.time / 1000); } lCount++; lastY = (float) chartYAvg; } // End if (session.time >= startTime && session.time <= endTime ) } // End for (BioSession session : sessionItems) //Draw high low dates if (highY != 0 && lowY != 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy"); String hDate = dateFormat.format(new Date((long) highTime * 1000L)); String lDate = dateFormat.format(new Date((long) lowTime * 1000L)); contentByte.beginText(); contentByte.setFontAndSize(baseFont, 8); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0); contentByte.endText(); } //Draw Regression Line RegressionResult regression = calculateRegression(ritems); contentByte.saveState(); contentByte.setRGBColorStrokeF(0, 0, 250); contentByte.setLineDash(3, 3, 0); contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept); contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept) + (float) (regression.slope * (chartWidth / xIncrement)))); contentByte.stroke(); contentByte.restoreState(); contentByte.setRGBColorStrokeF(0, 0, 0); // Log.e(TAG, keyName + ": [" + rawYValues + "]"); // Get ready for the next key (and series of database points ) verticalPos -= spaceHeight; if (verticalPos < 30) { document.newPage(); verticalPos = 780 - spaceHeight; } } // End for (int key = 0; key < maxKeys; key++) //document.add(new Paragraph("You can also write stuff directly tot he document like this!")); } catch (DocumentException de) { System.err.println(de.getMessage()); Log.e(TAG, de.toString()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); Log.e(TAG, ioe.toString()); } catch (Exception e) { System.err.println(e.getMessage()); Log.e(TAG, e.toString()); } // step 5: we close the document document.close(); fileExportCompleteHandler.sendEmptyMessage(EXPORT_SUCCESS); } }).start(); }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/****************************************************************************************************** * Adds the all pages.// ww w .ja va2 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:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java
License:GNU General Public License
/** * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, * com.lowagie.text.Document)/* ww w .j a v a 2s . c o m*/ */ public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); // write the headertable table.setTotalWidth(document.right() - document.left()); table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 20, cb); // compose the footer String text = writer.getPageNumber() + " / "; float textSize = helv.getWidthPoint(text, 12); float textBase = document.bottom() - 49; cb.beginText(); cb.setFontAndSize(helv, 12); float adjust = helv.getWidthPoint("0", 12); cb.setTextMatrix(document.right() - textSize - adjust - 5, textBase); cb.showText(text); cb.endText(); cb.addTemplate(tpl, document.right() - adjust, textBase); cb.saveState(); // draw a Rectangle around the page cb.setLineWidth(1); cb.rectangle(20, 20, document.getPageSize().getWidth() - 40, document.getPageSize().getHeight() - 40); cb.stroke(); cb.restoreState(); }
From source file:jm.web.Addons.java
License:GNU General Public License
public static void setEncabezado(PdfWriter writer, Document document, String texto) { if (writer.getPageNumber() > 1) { try {//from w w w. j a v a 2 s . c om PdfPTable encabezado = new PdfPTable(1); encabezado.setTotalWidth(document.right() - document.left() - 120); encabezado.addCell(Addons.setCeldaPDF(texto, Font.HELVETICA, 9, Font.BOLD, Element.ALIGN_LEFT, 0)); encabezado.writeSelectedRows(0, -1, 60, document.top() + 25, writer.getDirectContent()); PdfContentByte cb = writer.getDirectContent(); cb.setLineWidth(2); cb.moveTo(60, document.top() + 10); cb.lineTo(document.right() - document.left() - 58, document.top() + 10); } catch (Exception e) { throw new ExceptionConverter(e); } } }
From source file:joelib2.io.types.PDF.java
License:Open Source License
/** * Writes a molecule with his <tt>PairData</tt> . * * @param mol the molecule with additional data * @param title the molecule title or <tt>null</tt> if the title * from the molecule should be used * @param writePairData if <tt>true</tt> then the additional molecule data * is written//w w w . j a v a2s .c om * @param attribs2write Description of the Parameter * @return <tt>true</tt> if the molecule and the data has * been succesfully written. * @exception IOException Description of the Exception */ public boolean write(Molecule mol, String title, boolean writePairData, List attribs2write, SMARTSPatternMatcher smarts) throws IOException { if (firstMoleculeWritten == false) { document.open(); firstMoleculeWritten = true; } Dimension d = new Dimension(Mol2Image.instance().getDefaultWidth(), Mol2Image.instance().getDefaultHeight()); RenderingAtoms container = new RenderingAtoms(); container.add(mol); RenderHelper.translateAllPositive(container); RenderHelper.scaleMolecule(container, d, 0.8); RenderHelper.center(container, d); Renderer2D renderer = new Renderer2D(); //BaseFont helvetica = null; try { BaseFont.createFont("Helvetica", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int w = d.width; int h = d.height; PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2 = tp.createGraphics(w, h); g2.setStroke(new BasicStroke(0.1f)); tp.setWidth(w); tp.setHeight(h); g2.setColor(renderer.getRenderer2DModel().getBackColor()); g2.fillRect(0, 0, d.width, d.height); if (smarts != null) { renderer.selectSMARTSPatterns(container, smarts); } renderer.paintMolecule(container, g2); g2.dispose(); ////cb.addTemplate(tp, 72, 720 - h); //cb.addTemplate(tp, 12, 720 - h); cb.addTemplate(tp, 0, document.getPageSize().height() - h); // Mol2Image.instance().mol2image(mol); BaseFont bf = null; try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); } catch (DocumentException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } String string = ""; //float myBorder = DEFAULT_BORDER; //float fontSize = 10; //float fontSizeDelta = DEFAULT_FONT_OFFSET; float hpos; if (writePairData) { PairData pairData; PairDataIterator gdit = mol.genericDataIterator(); int index = 0; boolean firstPageWritten = false; List attributesV; if (attribs2write == null) { // write all descriptors attributesV = new Vector(); //DescResult tmpPropResult; while (gdit.hasNext()) { pairData = gdit.nextPairData(); attributesV.add(pairData.getKey()); } } else { attributesV = attribs2write; } // sort descriptors by attribute name String[] attributes = new String[attributesV.size()]; for (int i = 0; i < attributesV.size(); i++) { attributes[i] = (String) attributesV.get(i); } Arrays.sort(attributes); // write them for (int i = 0; i < attributes.length; i++) { pairData = mol.getData(attributes[i]); string = pairData.getKey() + " = " + pairData.toString(); // reduce too complex data string = string.replace('\n', ' '); string = string.substring(0, Math.min(string.length(), WRITE_MAX_CHARACTERS)); tp = cb.createTemplate(document.getPageSize().width() - pageBorder, fontSize + fontSizeDelta); tp.setFontAndSize(bf, fontSize); tp.beginText(); tp.setTextMatrix(0, fontSizeDelta); tp.showText(string); tp.endText(); cb.setLineWidth(1f); tp.moveTo(0, 0); tp.lineTo(document.getPageSize().width() - (2 * pageBorder), 0); tp.stroke(); if (firstPageWritten) { hpos = document.getPageSize().height() - ((fontSize + fontSizeDelta) * (index + 1)); } else { hpos = document.getPageSize().height() - h - ((fontSize + fontSizeDelta) * (index + 1)); } if (hpos < pageBorder) { index = 1; firstPageWritten = true; hpos = document.getPageSize().height() - ((fontSize + fontSizeDelta) * (index + 1)); try { document.newPage(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } cb.addTemplate(tp, pageBorder, hpos); index++; } } try { document.newPage(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (true); }