List of usage examples for com.lowagie.text Document getPageSize
public Rectangle getPageSize()
From source file:com.krawler.spring.exportFunctionality.exportMPXDAOImpl.java
License:Open Source License
public int addGroupableTable(JSONObject groupingConfig, String groupByField, String groupHeaderText, int stcol, int stpcol, int strow, int stprow, JSONArray store, String[] dataIndexArr, String[] colHeader, String[] widths, String[] align, Document document, HttpServletRequest request) throws ServiceException { try {/*from w w w . j a va2 s.co m*/ String groupSummaryField = groupingConfig.getString("groupSummaryField"); String groupSummaryText = groupingConfig.getString("groupSummaryText"); String reportSummaryField = groupingConfig.getString("reportSummaryField"); String reportSummaryText = groupingConfig.getString("reportSummaryText"); DateFormat formatter = authHandlerDAOObj.getUserDateFormatter( sessionHandlerImpl.getDateFormatID(request), sessionHandlerImpl.getTimeZoneDifference(request), true); DateFormat frmt = authHandler.getDateFormatter(request); String currencyid = sessionHandlerImpl.getCurrencyID(request); java.awt.Color tColor = new Color(Integer.parseInt(config.getString("textColor"), 16)); java.awt.Color gsBGColor = new Color(Integer.parseInt("E5E5E5", 16)); java.awt.Color rsBGColor = new Color(Integer.parseInt("808080", 16)); // fontRegular.setColor(tColor); PdfPTable table; float[] tcol; tcol = new float[colHeader.length + 1]; tcol[0] = 40; for (int i = 1; i < colHeader.length + 1; i++) { tcol[i] = Float.parseFloat(widths[i - 1]); } table = new PdfPTable(colHeader.length + 1); table.setWidthPercentage(tcol, document.getPageSize()); table.setSpacingBefore(15); PdfPCell h2 = new PdfPCell( new Paragraph(fontFamilySelector.process("No.", FontContext.TABLE_HEADER, tColor))); if (config.getBoolean("gridBorder")) { h2.setBorder(PdfPCell.BOX); } else { h2.setBorder(0); } h2.setPadding(4); h2.setBorderColor(Color.GRAY); h2.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(h2); PdfPCell h1 = null; for (int hcol = stcol; hcol < dataIndexArr.length; hcol++) { if (align[hcol].equals("currency") && !colHeader[hcol].equals("")) { String currency = currencyRender("", currencyid); h1 = new PdfPCell(new Paragraph(fontFamilySelector .process(colHeader[hcol] + "(" + currency + ")", FontContext.TABLE_HEADER, tColor))); } else { h1 = new PdfPCell(new Paragraph( fontFamilySelector.process(colHeader[hcol], FontContext.TABLE_HEADER, tColor))); } h1.setHorizontalAlignment(Element.ALIGN_CENTER); if (config.getBoolean("gridBorder")) { h1.setBorder(PdfPCell.BOX); } else { h1.setBorder(0); } h1.setBorderColor(Color.GRAY); h1.setPadding(4); table.addCell(h1); } table.setHeaderRows(1); String groupName = "", rowCurrency = ""; Double subTotal = 0.0; Double grandTotal = 0.0; int rowSpan = 0; for (int row = strow; row < stprow; row++) { rowSpan++; JSONObject rowData = store.getJSONObject(row); if (row == 0) { groupName = rowData.getString(groupByField); rowCurrency = rowData.has("currencyid") ? rowData.getString("currencyid") : currencyid; subTotal = 0.0; addGroupRow(groupHeaderText + ": " + groupName, currencyid, table, dataIndexArr); } if (!groupName.equalsIgnoreCase(rowData.getString(groupByField))) { addSummaryRow(groupSummaryText + groupName + " ", subTotal, rowCurrency, table, dataIndexArr, false, gsBGColor); groupName = rowData.getString(groupByField); rowCurrency = rowData.has("currencyid") ? rowData.getString("currencyid") : currencyid; addGroupRow(groupHeaderText + ": " + groupName, currencyid, table, dataIndexArr); subTotal = 0.0; rowSpan = 1; } subTotal += Double.parseDouble(rowData.getString(groupSummaryField)); grandTotal += Double.parseDouble(rowData.getString(reportSummaryField)); rowCurrency = rowData.has("currencyid") ? rowData.getString("currencyid") : currencyid; h2 = new PdfPCell(new Paragraph( fontFamilySelector.process(String.valueOf(row + 1), FontContext.TABLE_HEADER, tColor))); if (config.getBoolean("gridBorder")) { h2.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT); } else { h2.setBorder(0); } h2.setPadding(4); h2.setBorderColor(Color.GRAY); h2.setHorizontalAlignment(Element.ALIGN_CENTER); h2.setVerticalAlignment(Element.ALIGN_CENTER); table.addCell(h2); for (int col = 0; col < dataIndexArr.length; col++) { String cellData = null; if (align[col].equals("currency") && !rowData.getString(dataIndexArr[col]).equals("")) { cellData = currencyRender(rowData.getString(dataIndexArr[col]), rowData.getString("currencyid")); } else if (align[col].equals("date") && !rowData.getString(dataIndexArr[col]).equals("")) { try { cellData = formatter.format(frmt.parse(rowData.getString(dataIndexArr[col]))); } catch (Exception ex) { cellData = rowData.getString(dataIndexArr[col]); } } else { cellData = rowData.getString(dataIndexArr[col]); } Paragraph para = new Paragraph( fontFamilySelector.process(cellData, FontContext.TABLE_HEADER, tColor)); h1 = new PdfPCell(para); if (config.getBoolean("gridBorder")) { h1.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT); } else { h1.setBorder(0); } h1.setPadding(4); h1.setBorderColor(Color.GRAY); if (!align[col].equals("currency") && !align[col].equals("date")) { h1.setHorizontalAlignment(Element.ALIGN_LEFT); h1.setVerticalAlignment(Element.ALIGN_LEFT); } else if (align[col].equals("currency")) { h1.setHorizontalAlignment(Element.ALIGN_RIGHT); h1.setVerticalAlignment(Element.ALIGN_RIGHT); } else if (align[col].equals("date")) { h1.setHorizontalAlignment(Element.ALIGN_CENTER); h1.setVerticalAlignment(Element.ALIGN_CENTER); } table.addCell(h1); } } if (rowSpan > 0) { addSummaryRow(groupSummaryText + groupName + " ", subTotal, rowCurrency, table, dataIndexArr, false, gsBGColor); } addSummaryRow(reportSummaryText, grandTotal, currencyid, table, dataIndexArr, false, rsBGColor); document.add(table); document.newPage(); } catch (Exception e) { throw ServiceException.FAILURE("exportDAOImpl.addTable", e); } return stpcol; }
From source file:com.krawler.spring.exportFunctionality.exportMPXDAOImpl.java
License:Open Source License
public ByteArrayOutputStream getPdfData(JSONObject grid, HttpServletRequest request, JSONObject obj) throws ServiceException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = null;/*from w w w . jav a 2 s . c om*/ Document document = null; try { JSONArray gridmap = grid == null ? null : grid.getJSONArray("data"); String colHeader = ""; String colHeaderFinal = ""; String fieldListFinal = ""; String fieldList = ""; String width = ""; String align = ""; String alignFinal = ""; String widthFinal = ""; String colHeaderArrStr[] = null; String dataIndexArrStr[] = null; String widthArrStr[] = null; String alignArrStr[] = null; int strLength = 0; float totalWidth = 0; config = new com.krawler.utils.json.base.JSONObject(request.getParameter("config")); document = null; Rectangle rec = null; if (config.getBoolean("landscape")) { Rectangle recPage = new Rectangle(PageSize.A4.rotate()); recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16))); document = new Document(recPage, 15, 15, 30, 30); rec = document.getPageSize(); totalWidth = rec.getWidth(); } else { Rectangle recPage = new Rectangle(PageSize.A4); recPage.setBackgroundColor(new java.awt.Color(Integer.parseInt(config.getString("bgColor"), 16))); document = new Document(recPage, 15, 15, 30, 30); rec = document.getPageSize(); totalWidth = rec.getWidth(); } writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new EndPage()); document.open(); if (config.getBoolean("showLogo")) { addComponyLogo(document, request); } addTitleSubtitle(document); if (gridmap != null) { int givenTotalWidth = 0; for (int i = 0; i < gridmap.length(); i++) { JSONObject temp = gridmap.getJSONObject(i); givenTotalWidth += Integer.parseInt(temp.getString("width")); } double widthRatio = 1; if (givenTotalWidth > (totalWidth - 40.00)) { widthRatio = (totalWidth - 40.00) / givenTotalWidth; // 40.00 is left + right + table margin [15+15+10] margins of documents } for (int i = 0; i < gridmap.length(); i++) { JSONObject temp = gridmap.getJSONObject(i); colHeader += StringUtil.serverHTMLStripper(temp.getString("title")); if (colHeader.indexOf("*") != -1) { colHeader = colHeader.substring(0, colHeader.indexOf("*") - 1) + ","; } else { colHeader += ","; } fieldList += temp.getString("header") + ","; if (!config.getBoolean("landscape")) { int totalWidth1 = (int) ((totalWidth / gridmap.length()) - 5.00); width += "" + totalWidth1 + ","; //resize according to page view[potrait] } else { double adjustedWidth = (Integer.parseInt(temp.getString("width")) * widthRatio); width += ((int) Math.floor(adjustedWidth)) + ","; } if (temp.getString("align").equals("")) { align += "none" + ","; } else { align += temp.getString("align") + ","; } } strLength = colHeader.length() - 1; colHeaderFinal = colHeader.substring(0, strLength); strLength = fieldList.length() - 1; fieldListFinal = fieldList.substring(0, strLength); strLength = width.length() - 1; widthFinal = width.substring(0, strLength); strLength = align.length() - 1; alignFinal = align.substring(0, strLength); colHeaderArrStr = colHeaderFinal.split(","); dataIndexArrStr = fieldListFinal.split(","); widthArrStr = widthFinal.split(","); alignArrStr = alignFinal.split(","); } else { fieldList = request.getParameter("header"); colHeader = request.getParameter("title"); width = request.getParameter("width"); align = request.getParameter("align"); colHeaderArrStr = colHeader.split(","); dataIndexArrStr = fieldList.split(","); widthArrStr = width.split(","); alignArrStr = align.split(","); } JSONArray store = obj.getJSONArray("data"); if (grid != null && grid.has("groupdata")) { JSONObject groupingConfig = grid.getJSONObject("groupdata"); addGroupableTable(groupingConfig, 0, colHeaderArrStr.length, 0, store.length(), store, dataIndexArrStr, colHeaderArrStr, widthArrStr, alignArrStr, document, request); } else { addTable(0, colHeaderArrStr.length, 0, store.length(), store, dataIndexArrStr, colHeaderArrStr, widthArrStr, alignArrStr, document, request); } } catch (Exception e) { throw ServiceException.FAILURE("exportMPXDAOImpl.getPdfData", e); } finally { if (document != null) { document.close(); } if (writer != null) { writer.close(); } } return baos; }
From source file:com.matic.sudoku.io.export.PdfExporter.java
License:Open Source License
/** * Write board contents to PDF//www . ja va2 s.c o m * * @param board The board to write * @param targetFile Target output PDF file to write to * @throws DocumentException If any PDF library error occurs * @throws IOException If any error occurs while writing the PDF file */ public void write(final Board board, final File targetFile) throws DocumentException, IOException { //FontFactory.defaultEmbedding = true; final Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN); final OutputStream outputStream = new FileOutputStream(targetFile); final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); document.open(); final PdfContentByte contentByte = pdfWriter.getDirectContent(); final Rectangle pageSize = document.getPageSize(); final float pageHeight = pageSize.getHeight(); final float pageWidth = pageSize.getWidth(); contentByte.saveState(); final Graphics2D g2d = contentByte.createGraphics(pageWidth, pageHeight); board.setSize((int) pageWidth, (int) pageWidth); board.handleResized(); final int puzzleWidth = board.getPuzzleWidth(); //Calculate x and y coordinates for centered game board final int originX = (int) (pageWidth / 2 - (puzzleWidth / 2)); final int originY = (int) ((pageHeight / 2) - (puzzleWidth / 2)); board.setDrawingOrigin(originX, originY); board.draw(g2d, true, false); contentByte.restoreState(); g2d.dispose(); document.close(); outputStream.flush(); outputStream.close(); }
From source file:com.matic.sudoku.io.export.PdfExporter.java
License:Open Source License
/** * Generate and export multiple boards to PDF * /* w w w . jav a 2 s . c o m*/ * @param exporterParameters PDF exporter parameters * @param generator Generator used for puzzle generation * @throws IOException If any PDF library error occurs * @throws DocumentException If any error occurs while writing the PDF file */ public void write(final ExporterParameters exporterParameters, final Generator generator, final int boardDimension) throws IOException, DocumentException { //How many PDF-pages are needed to fit all puzzles using the desired page formatting final int optimisticPageCount = exporterParameters.getPuzzleCount() / exporterParameters.getPuzzlesPerPage(); final int pageCount = exporterParameters.getPuzzleCount() % exporterParameters.getPuzzlesPerPage() > 0 ? optimisticPageCount + 1 : optimisticPageCount; final Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN); final OutputStream outputStream = new FileOutputStream(exporterParameters.getOutputPath()); final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); final String creator = Sudoku.getNameAndVersion(); document.addSubject("Puzzles generated by " + creator); document.addCreator(creator); document.open(); final Rectangle pageSize = document.getPageSize(); final int pageHeight = (int) pageSize.getHeight(); final int pageWidth = (int) pageSize.getWidth(); //Get appropriate number of rows and columns needed to divide a page into final int horizontalDimension = exporterParameters.getPuzzlesPerPage() > 2 ? 2 : 1; final int verticalDimension = exporterParameters.getPuzzlesPerPage() > 1 ? 2 : 1; //Get available space for each board (with margins) on a page final int boardWidth = pageWidth / horizontalDimension; final int boardHeight = pageHeight / verticalDimension; final Board board = new Board(boardDimension, SymbolType.DIGITS); board.setSize(boardWidth, boardHeight); board.handleResized(); //Get available height/width on a page for a puzzle itself final int puzzleWidth = board.getPuzzleWidth(); int puzzlesPrinted = 0; final PdfContentByte contentByte = pdfWriter.getDirectContent(); final Grading[] gradings = getGeneratedPuzzleGradings(exporterParameters.getGradings(), exporterParameters.getOrdering(), exporterParameters.getPuzzleCount()); pageCounter: for (int page = 0; page < pageCount; ++page) { document.newPage(); final Graphics2D g2d = contentByte.createGraphics(pageWidth, pageHeight); for (int y = 0, i = 0; i < verticalDimension; y += boardHeight, ++i) { for (int x = 0, j = 0; j < horizontalDimension; x += boardWidth, ++j) { //Check whether to generate a new puzzle or print empty boards final ExportMode exportMode = exporterParameters.getExportMode(); final Grading selectedGrading = exportMode == ExportMode.BLANK ? null : gradings[puzzlesPrinted]; if (exportMode == ExportMode.GENERATE_NEW) { board.setPuzzle(generatePuzzle(generator, getSymmetry(exporterParameters.getSymmetries()), selectedGrading)); board.recordGivens(); } //Calculate puzzle drawing origins final int originX = x + (int) (boardWidth / 2 - (puzzleWidth / 2)); final int originY = y + (int) (boardHeight / 2) - (puzzleWidth / 2); board.setSymbolType(getSymbolType(exporterParameters.getSymbolType())); board.setDrawingOrigin(originX, originY); board.draw(g2d, false, false); drawLegend(g2d, getLegendString(exporterParameters.isShowNumbering(), exporterParameters.isShowGrading(), puzzlesPrinted + 1, selectedGrading), originX, originY, puzzleWidth); if (++puzzlesPrinted == exporterParameters.getPuzzleCount()) { //We've printed all puzzles, break g2d.dispose(); break pageCounter; } } } g2d.dispose(); } document.close(); outputStream.flush(); outputStream.close(); }
From source file:CPS.Core.TODOLists.PDFExporter.java
License:Open Source License
private Document prepareDocument(String filename, final String title, final String author, final String creator, final Rectangle pageSize) { System.out.println("DEBUG(PDFExporter): Creating document: " + filename); Document d = new Document(); d.setPageSize(pageSize);/*ww w. j a v a 2s . com*/ // TODO alter page orientation? maybe useful for seed order worksheet d.addTitle(title); d.addAuthor(author); // d.addSubject( ); // d.addKeywords( ); d.addCreator(creator); // left, right, top, bottom - scale in points (~72 points/inch) d.setMargins(35, 35, 35, 44); try { PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(filename)); // add header and footer writer.setPageEvent(new PdfPageEventHelper() { public void onEndPage(PdfWriter writer, Document document) { try { Rectangle page = document.getPageSize(); PdfPTable head = new PdfPTable(3); head.getDefaultCell().setBorderWidth(0); head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT); head.addCell(new Phrase(author, fontHeadFootItal)); head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER); head.addCell(new Phrase(title, fontHeadFootReg)); head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); head.addCell(""); head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent()); PdfPTable foot = new PdfPTable(3); foot.getDefaultCell().setBorderWidth(0); foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT); foot.addCell(new Phrase(creator, fontHeadFootItal)); foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER); foot.addCell(""); foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); foot.addCell(new Phrase("Page " + document.getPageNumber(), fontHeadFootReg)); foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent()); } catch (Exception e) { throw new ExceptionConverter(e); } } }); } catch (Exception e) { e.printStackTrace(); } return d; }
From source file:cz.incad.kramerius.pdf.commands.render.RenderPDF.java
License:Open Source License
public static Float ratio(Document document, float percentage, com.lowagie.text.Image img) { Float wratio = document.getPageSize().getWidth() / img.getWidth(); Float hratio = document.getPageSize().getHeight() / img.getHeight(); Float ratio = Math.min(wratio, hratio); if (percentage != 1.0) { ratio = ratio * percentage;/*from w w w.j av a 2s . c o m*/ } return ratio; }
From source file:cz.incad.kramerius.pdf.impl.AbstractPDFRenderSupport.java
License:Open Source License
public static ScaledImageOptions insertJavaImage(Document document, float percentage, BufferedImage javaImg) throws IOException, BadElementException, MalformedURLException, DocumentException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); writeImageToStream(javaImg, "jpeg", bos); com.lowagie.text.Image img = com.lowagie.text.Image.getInstance(bos.toByteArray()); Float ratio = ratio(document, percentage, javaImg); int fitToPageWidth = (int) (javaImg.getWidth(null) * ratio); int fitToPageHeight = (int) (javaImg.getHeight(null) * ratio); int offsetX = ((int) document.getPageSize().getWidth() - fitToPageWidth) / 2; int offsetY = ((int) document.getPageSize().getHeight() - fitToPageHeight) / 2; img.scaleAbsoluteHeight(ratio * img.getHeight()); img.scaleAbsoluteWidth(ratio * img.getWidth()); img.setAbsolutePosition((offsetX),/*w w w. j a v a 2s.co m*/ document.getPageSize().getHeight() - offsetY - (ratio * img.getHeight())); document.add(img); ScaledImageOptions options = new ScaledImageOptions(); options.setXdpi(img.getDpiX()); options.setYdpi(img.getDpiY()); options.setXoffset(offsetX); options.setYoffset(offsetY); options.setWidth(fitToPageWidth); options.setHeight(fitToPageHeight); options.setScaleFactor(ratio); return options; }
From source file:cz.incad.kramerius.pdf.impl.AbstractPDFRenderSupport.java
License:Open Source License
public static Float ratio(Document document, float percentage, BufferedImage javaImg) { Float wratio = document.getPageSize().getWidth() / javaImg.getWidth(null); Float hratio = document.getPageSize().getHeight() / javaImg.getHeight(null); Float ratio = Math.min(wratio, hratio); if (percentage != 1.0) { ratio = ratio * percentage;//from ww w . ja v a 2 s . c o m } return ratio; }
From source file:cz.incad.kramerius.rest.api.k5.client.pdf.PDFResource.java
License:Open Source License
private static StreamingOutput streamingOutput(final File file, final String format) { return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { try { Rectangle formatRect = formatRect(format); Document document = new Document(formatRect); PdfWriter.getInstance(document, output); document.open();//from w w w .j a v a 2 s .c o m Image image = Image.getInstance(file.toURI().toURL()); image.scaleToFit( document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(), document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin()); document.add(image); document.close(); } catch (Exception e) { throw new WebApplicationException(e); } finally { if (file != null) file.delete(); } } }; }
From source file:de.cuseb.bilderbuch.pdf.PdfController.java
License:Open Source License
@RequestMapping(value = "/pdf", method = RequestMethod.GET) public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) { try {//from w w w . jav a 2s. com PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest"); httpServletResponse.setContentType("application/pdf"); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream()); writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB); //document.addAuthor(pdfRequest.getAuthor()); //document.addTitle(pdfRequest.getTitle()); document.setPageSize( new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148))); document.open(); FontFactory.defaultEmbedding = true; FontFactory.register("IndieRock.ttf", "IndieRock"); Font font = FontFactory.getFont("IndieRock"); BaseFont baseFont = font.getBaseFont(); PdfContentByte cb = writer.getDirectContent(); Iterator<PdfPage> pages = pdfRequest.getPages().iterator(); while (pages.hasNext()) { PdfPage page = pages.next(); if (page.getImage() != null) { Image image = Image.getInstance(new URL(page.getImage().getUrl())); image.setDpi(300, 300); image.setAbsolutePosition(0f, 0f); image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight()); document.add(image); cb.saveState(); cb.beginText(); cb.setColorFill(Color.WHITE); cb.moveText(10f, 10f); cb.setFontAndSize(baseFont, 18); cb.showText(page.getSentence()); cb.endText(); cb.restoreState(); if (pages.hasNext()) { document.newPage(); } } } document.close(); } catch (Exception e) { e.printStackTrace(); } }