List of usage examples for com.lowagie.text Rectangle getWidth
public float getWidth()
From source file:br.gov.jfrj.itextpdf.Documento.java
License:Open Source License
public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito, boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal, Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException { PdfReader pdfIn = new PdfReader(abPdf); Document doc = new Document(PageSize.A4, 0, 0, 0, 0); // final SimpleDateFormat sdf = new SimpleDateFormat( // "EEE MMM dd HH:mm:ss zzz yyyy"); // doc.add(new Meta("creationdate", sdf.format(new Date(0L)))); final ByteArrayOutputStream boA4 = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(doc, boA4); doc.open();/* w w w . j a v a2 s .c om*/ PdfContentByte cb = writer.getDirectContent(); // Resize every page to A4 size // // double thetaRotation = 0.0; for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) { int rot = pdfIn.getPageRotation(i); float left = pdfIn.getPageSize(i).getLeft(); float bottom = pdfIn.getPageSize(i).getBottom(); float top = pdfIn.getPageSize(i).getTop(); float right = pdfIn.getPageSize(i).getRight(); PdfImportedPage page = writer.getImportedPage(pdfIn, i); float w = page.getWidth(); float h = page.getHeight(); // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w // + ", " + h); doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4); doc.newPage(); cb.saveState(); if (rot != 0 && rot != 180) { float swap = w; w = h; h = swap; } float pw = doc.getPageSize().getWidth(); float ph = doc.getPageSize().getHeight(); double scale = Math.min(pw / w, ph / h); // do my transformations : cb.transform(AffineTransform.getScaleInstance(scale, scale)); if (!internoProduzido) { cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN)); cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN)); } if (rot != 0) { double theta = -rot * (Math.PI / 180); if (rot == 180) { cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2)); } else { cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2)); } if (rot == 90) { cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2)); } else if (rot == 270) { cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2)); } } // Logger.getRootLogger().error( // "----- dimensoes: " + rot + ", " + w + ", " + h); // Logger.getRootLogger().error("----- page: " + pw + ", " + ph); // cb.transform(AffineTransform.getTranslateInstance( // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2)); // put the page cb.addTemplate(page, 0, 0); // draw a red rectangle at the page borders // // cb.saveState(); // cb.setColorStroke(Color.red); // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i) // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn // .getPageSize(i).getTop()); // cb.stroke(); // cb.restoreState(); cb.restoreState(); } doc.close(); abPdf = boA4.toByteArray(); final ByteArrayOutputStream bo2 = new ByteArrayOutputStream(); final PdfReader reader = new PdfReader(abPdf); final int n = reader.getNumberOfPages(); final PdfStamper stamp = new PdfStamper(reader, bo2); // adding content to each page int i = 0; PdfContentByte under; PdfContentByte over; final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false); // Image img = Image.getInstance("watermark.jpg"); final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); byte maskr[] = { (byte) 0xff }; Image mask = Image.getInstance(1, 1, 1, 1, maskr); mask.makeMask(); mask.setInverted(true); while (i < n) { i++; // watermark under the existing page under = stamp.getUnderContent(i); over = stamp.getOverContent(i); final Barcode39 code39 = new Barcode39(); // code39.setCode(doc.getCodigo()); code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", "")); code39.setStartStopText(false); final Image image39 = code39.createImageWithBarcode(over, null, null); Rectangle r = stamp.getReader().getPageSizeWithRotation(i); image39.setInitialRotation((float) Math.PI / 2.0f); image39.setAbsolutePosition( r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT, BARCODE_HEIGHT_IN_CM * CM_UNIT); image39.setBackgroundColor(Color.green); image39.setBorderColor(Color.RED); image39.setBorderWidth(0.5f * CM_UNIT); image39.setImageMask(mask); over.setRGBColorFill(255, 255, 255); mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT, (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT); mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT, image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT); over.addImage(mask); over.setRGBColorFill(0, 0, 0); over.addImage(image39); // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0, // mask.getScaledHeight() * 8, 100, 450); if (qrCode != null) { java.awt.Image imgQRCode = createQRCodeImage(qrCode); Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true); imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT); imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT); over.setRGBColorFill(255, 255, 255); mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT, (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT); mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT, (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT); over.addImage(mask); over.setRGBColorFill(0, 0, 0); over.addImage(imageQRCode); } if (mensagem != null) { PdfPTable table = new PdfPTable(1); table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT); PdfPCell cell = new PdfPCell(new Paragraph(mensagem, FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK))); cell.setBorderWidth(0); table.addCell(cell); over.setRGBColorFill(255, 255, 255); mask.setAbsolutePosition( (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT, (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT); mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(), 2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight()); over.addImage(mask); over.setRGBColorFill(0, 0, 0); table.writeSelectedRows(0, -1, (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT, table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over); } if (cancelado) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } else if (rascunho) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } else if (semEfeito) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } // if (!rascunho // && request.getRequestURL().indexOf("http://laguna/") == -1) { if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false")) || (!Contexto.resource("isBaseTest").equals("false")))) { over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); over.setGState(gs); over.setColorFill(Color.GRAY); over.beginText(); over.setFontAndSize(helv, 72); over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45); over.endText(); over.restoreState(); } // Imprime um circulo com o numero da pagina dentro. if (paginaInicial != null) { String sFl = String.valueOf(paginaInicial + i - 1); // Se for a ultima pagina e o numero nao casar, acrescenta "-" e // pagina final if (n == i) { if (paginaFinal != paginaInicial + n - 1) { sFl = sFl + "-" + String.valueOf(paginaFinal); } } if (i > cOmitirNumeracao) { // Raio do circulo interno final float radius = 18f; // Distancia entre o circulo interno e o externo final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT), helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT)) - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT), helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT)) + 2 * TEXT_TO_CIRCLE_INTERSPACE; // Centro do circulo float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace); float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace); over.saveState(); final PdfGState gs = new PdfGState(); gs.setFillOpacity(1f); over.setGState(gs); over.setColorFill(Color.BLACK); over.saveState(); over.setColorStroke(Color.black); over.setLineWidth(1f); over.setColorFill(Color.WHITE); // Circulo externo over.circle(xCenter, yCenter, radius + circleInterspace); over.fill(); over.circle(xCenter, yCenter, radius + circleInterspace); over.stroke(); // Circulo interno over.circle(xCenter, yCenter, radius); over.stroke(); over.restoreState(); { over.saveState(); over.beginText(); over.setFontAndSize(helv, TEXT_HEIGHT); // Escreve o texto superior do carimbo float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT); showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter, radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true); // Escreve o texto inferior float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT); showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter, radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false); over.endText(); over.restoreState(); } over.beginText(); int textHeight = 23; // Diminui o tamanho do font ate que o texto caiba dentro do // circulo interno while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE))) textHeight--; float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight); over.setFontAndSize(helv, textHeight); over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0); over.endText(); over.restoreState(); } } } stamp.close(); return bo2.toByteArray(); }
From source file:br.org.acessobrasil.silvinha.util.HeaderAndFooter.java
License:Open Source License
/** * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) *//* w ww . ja v a2s . c o m*/ public void onEndPage(PdfWriter writer, Document document) { try { Rectangle page = document.getPageSize(); PdfPTable head = new PdfPTable(1); PdfPCell cell = new PdfPCell(new Paragraph(GERAL.RELATORIOS_ASES)); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); cell.setBorder(Rectangle.BOTTOM); head.addCell(cell); 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(1); cell = new PdfPCell(new Paragraph(String.valueOf(document.getPageNumber()))); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER); cell.setBorder(Rectangle.TOP); foot.addCell(cell); 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); } }
From source file:classroom.filmfestival_c.Movies19.java
@SuppressWarnings("unchecked") protected static void createSheet(Session session, Date date, PdfWriter writer) { Query q;// ww w .ja v a 2s . c o m q = session.createQuery( "select distinct screening.id.place from FestivalScreening as screening where id.day=? order by screening.id.place"); q.setDate(0, date); List<String> places = q.list(); Rectangle art = writer.getBoxSize("art"); // initialize the dimensions for this day float top = art.getTop(); float row_height = art.getHeight() / places.size(); if (row_height > 70) { row_height = 70; } float column_width = art.getWidth() / COLUMNS; float left = art.getLeft() + column_width; float minute = (2f * column_width) / 60f; // content drawGrid(writer, places, date.toString(), left, column_width, top, row_height); q = session.createQuery("from FestivalScreening where id.day=? order by id.time, id.place"); q.setDate(0, date); List<FestivalScreening> screenings = q.list(); for (FestivalScreening screening : screenings) { try { drawMovie(writer, screening, places, minute, left, top, row_height); } catch (DocumentException e) { LOGGER.error("DocumentException: ", e); } } }
From source file:clusterMaker.treeview.dendroview.GraphicsExportPanel.java
License:Open Source License
private void pdfSave(String format) { com.lowagie.text.Rectangle pageSize = PageSize.LETTER; Document document = new Document(pageSize); try {/*from w w w. j av a 2s .co m*/ OutputStream output = new BufferedOutputStream(new FileOutputStream(getFile())); PdfWriter writer = PdfWriter.getInstance(document, output); document.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D g = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight(), new DefaultFontMapper()); double imageScale = Math.min(pageSize.getWidth() / ((double) estimateWidth() + getBorderPixels()), pageSize.getHeight() / ((double) estimateHeight() + getBorderPixels())); g.scale(imageScale, imageScale); drawAll(g, 1.0); g.dispose(); } catch (Exception e) { JOptionPane.showMessageDialog(this, new JTextArea("Dendrogram export had problem " + e)); logger.error("Exception " + e); // e.printStackTrace(); } document.close(); }
From source file:clusterMaker.treeview.dendroview.GraphicsExportPanel.java
License:Open Source License
private void epsSave(String format) { com.lowagie.text.Rectangle pageSize = PageSize.LETTER; Properties p = new Properties(); p.setProperty(PSGraphics2D.PAGE_SIZE, "Letter"); p.setProperty("org.freehep.graphicsio.AbstractVectorGraphicsIO.TEXT_AS_SHAPES", Boolean.toString(false)); try {//from ww w.j a va2s . c om OutputStream output = new BufferedOutputStream(new FileOutputStream(getFile())); PSGraphics2D g = new PSGraphics2D(output, view); double imageScale = Math.min(pageSize.getWidth() / ((double) estimateWidth() + getBorderPixels()), pageSize.getHeight() / ((double) estimateHeight() + getBorderPixels())); g.setMultiPage(false); g.setProperties(p); g.startExport(); g.scale(imageScale, imageScale); drawAll(g, 1.0); g.endExport(); output.close(); } catch (Exception e) { JOptionPane.showMessageDialog(this, new JTextArea("Dendrogram export had problem " + e)); logger.error("Exception " + e); // e.printStackTrace(); } }
From source file:clusterMaker.treeview.dendroview.GraphicsExportPanel.java
License:Open Source License
private void svgSave(String format) { com.lowagie.text.Rectangle pageSize = PageSize.LETTER; Properties p = new Properties(); p.setProperty(PSGraphics2D.PAGE_SIZE, "Letter"); p.setProperty("org.freehep.graphicsio.AbstractVectorGraphicsIO.TEXT_AS_SHAPES", Boolean.toString(false)); try {// ww w . j a va 2 s .c o m OutputStream output = new BufferedOutputStream(new FileOutputStream(getFile())); SVGGraphics2D g = new SVGGraphics2D(output, view); double imageScale = Math.min(pageSize.getWidth() / ((double) estimateWidth() + getBorderPixels()), pageSize.getHeight() / ((double) estimateHeight() + getBorderPixels())); g.setProperties(p); g.startExport(); g.scale(imageScale, imageScale); drawAll(g, 1.0); g.endExport(); output.close(); } catch (Exception e) { JOptionPane.showMessageDialog(this, new JTextArea("Dendrogram export had problem " + e)); logger.error("Exception " + e); // e.printStackTrace(); } }
From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java
License:Open Source License
public static void convertHSSF2Pdf(Workbook wb, String header, File reportFile) throws Exception { assert wb != null; assert reportFile != null; //Precompute formula FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); for (int i = 0; i < wb.getNumberOfSheets(); i++) { Sheet sheet = wb.getSheetAt(i);//from w ww. jav a 2 s . co m for (Row r : sheet) { for (Cell c : r) { if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) { try { evaluator.evaluateFormulaCell(c); } catch (Exception e) { System.err.println(e); } } } } } File tmp = File.createTempFile("tmp_", ".xlsx"); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tmp))) { wb.write(out); } //Find page orientation int maxColumnsGlobal = 0; for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) { Sheet sheet = wb.getSheetAt(sheetNo); for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) { Row row = rowIterator.next(); maxColumnsGlobal = Math.max(maxColumnsGlobal, row.getLastCellNum()); } } Rectangle pageSize = maxColumnsGlobal < 10 ? PageSize.A4 : PageSize.A4.rotate(); Document pdfDocument = new Document(pageSize, 10f, 10f, 20f, 20f); PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(reportFile)); addHeader(writer, header); pdfDocument.open(); //we have two columns in the Excel sheet, so we create a PDF table with two columns //Note: There are ways to make this dynamic in nature, if you want to. //Loop through sheets for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) { Sheet sheet = wb.getSheetAt(sheetNo); //Loop through rows, to find number of columns int minColumns = 1000; int maxColumns = 0; for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) { Row row = rowIterator.next(); if (row.getFirstCellNum() >= 0) minColumns = Math.min(minColumns, row.getFirstCellNum()); if (row.getLastCellNum() >= 0) maxColumns = Math.max(maxColumns, row.getLastCellNum()); } if (maxColumns == 0) continue; //Loop through first rows, to find relative width float[] widths = new float[maxColumns]; int totalWidth = 0; for (int c = 0; c < maxColumns; c++) { int w = sheet.getColumnWidth(c); widths[c] = w; totalWidth += w; } for (int c = 0; c < maxColumns; c++) { widths[c] /= totalWidth; } //Create new page and a new chapter with the sheet's name if (sheetNo > 0) pdfDocument.newPage(); Chapter pdfSheet = new Chapter(sheet.getSheetName(), sheetNo + 1); PdfPTable pdfTable = null; PdfPCell pdfCell = null; boolean inTable = false; //Loop through cells, to create the content // boolean leftBorder = true; // boolean[] topBorder = new boolean[maxColumns+1]; for (int r = 0; r <= sheet.getLastRowNum(); r++) { Row row = sheet.getRow(r); //Check if we exited a table (empty line) if (row == null) { if (pdfTable != null) { addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable); pdfTable = null; } inTable = false; continue; } //Check if we start a table (>MIN_COL_IN_TABLE columns) if (row.getLastCellNum() >= MIN_COL_IN_TABLE) { inTable = true; } if (!inTable) { //Process the data outside table, just add the text boolean hasData = false; Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (cell.getCellType() == Cell.CELL_TYPE_BLANK) continue; Chunk chunk = getChunk(wb, cell); pdfSheet.add(chunk); pdfSheet.add(new Chunk(" ")); hasData = true; } if (hasData) pdfSheet.add(Chunk.NEWLINE); } else { //Process the data in table if (pdfTable == null) { //Create table pdfTable = new PdfPTable(maxColumns); pdfTable.setWidths(widths); // topBorder = new boolean[maxColumns+1]; } int cellNumber = minColumns; // leftBorder = false; Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); for (; cellNumber < cell.getColumnIndex(); cellNumber++) { pdfCell = new PdfPCell(); pdfCell.setBorder(0); pdfTable.addCell(pdfCell); } Chunk phrase = getChunk(wb, cell); pdfCell = new PdfPCell(new Phrase(phrase)); pdfCell.setFixedHeight(row.getHeightInPoints() - 3); pdfCell.setNoWrap(!cell.getCellStyle().getWrapText()); pdfCell.setPaddingLeft(1); pdfCell.setHorizontalAlignment( cell.getCellStyle().getAlignment() == CellStyle.ALIGN_CENTER ? PdfPCell.ALIGN_CENTER : cell.getCellStyle().getAlignment() == CellStyle.ALIGN_RIGHT ? PdfPCell.ALIGN_RIGHT : PdfPCell.ALIGN_LEFT); pdfCell.setUseBorderPadding(false); pdfCell.setUseVariableBorders(false); pdfCell.setBorderWidthRight(cell.getCellStyle().getBorderRight() == 0 ? 0 : .5f); pdfCell.setBorderWidthBottom(cell.getCellStyle().getBorderBottom() == 0 ? 0 : cell.getCellStyle().getBorderBottom() > 1 ? 1 : .5f); pdfCell.setBorderWidthLeft(cell.getCellStyle().getBorderLeft() == 0 ? 0 : cell.getCellStyle().getBorderLeft() > 1 ? 1 : .5f); pdfCell.setBorderWidthTop(cell.getCellStyle().getBorderTop() == 0 ? 0 : cell.getCellStyle().getBorderTop() > 1 ? 1 : .5f); String color = cell.getCellStyle().getFillForegroundColorColor() == null ? null : ((XSSFColor) cell.getCellStyle().getFillForegroundColorColor()).getARGBHex(); if (color != null) pdfCell.setBackgroundColor(new Color(Integer.decode("0x" + color.substring(2)))); pdfTable.addCell(pdfCell); cellNumber++; } for (; cellNumber < maxColumns; cellNumber++) { pdfCell = new PdfPCell(); pdfCell.setBorder(0); pdfTable.addCell(pdfCell); } } //Custom code to add all images on the first sheet (works for reporting) if (sheetNo == 0 && row.getRowNum() == 0) { for (PictureData pd : wb.getAllPictures()) { try { Image pdfImg = Image.getInstance(pd.getData()); pdfImg.scaleToFit( pageSize.getWidth() * .8f - pageSize.getBorderWidthLeft() - pageSize.getBorderWidthRight(), pageSize.getHeight() * .8f - pageSize.getBorderWidthTop() - pageSize.getBorderWidthBottom()); pdfSheet.add(pdfImg); } catch (Exception e) { e.printStackTrace(); } } } } if (pdfTable != null) { addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable); } pdfDocument.add(pdfSheet); } pdfDocument.close(); }
From source file:com.amphisoft.epub2pdf.content.XhtmlHandler.java
License:Open Source License
private void handleImage(String url, String alt, String borderWidth, String alignment) throws DocumentException { float marginTopPt = document.topMargin(); float marginBottomPt = document.bottomMargin(); float marginLeftPt = document.leftMargin(); float marginRightPt = document.rightMargin(); if (url == null) return;/*from ww w .j a v a 2 s .co m*/ Image img = null; String imgSimpleName = ""; try { File imgFile = new File(xhtmlDir, url); String imgPath = imgFile.getCanonicalPath(); imgSimpleName = imgFile.getName(); img = Image.getInstance(imgPath); if (alt == null) { alt = imgSimpleName; } img.setAlt(alt); } catch (Exception e) { printlnerr("epub2pdf: problem adding image " + imgSimpleName + ": " + e.getMessage()); return; } if (borderWidth != null) { int border = Integer.parseInt(borderWidth); if (border == 0) { img.setBorder(Image.NO_BORDER); } else { img.setBorder(Image.BOX); img.setBorderWidth(border); } } if (alignment != null) { int align = Image.DEFAULT; if (ElementTags.ALIGN_LEFT.equalsIgnoreCase(alignment)) align = Image.LEFT; else if (ElementTags.ALIGN_RIGHT.equalsIgnoreCase(alignment)) align = Image.RIGHT; else if (ElementTags.ALIGN_MIDDLE.equalsIgnoreCase(alignment)) align = Image.MIDDLE; img.setAlignment(align | Image.TEXTWRAP); } else { img.setAlignment(Image.MIDDLE); } Rectangle pageRect = document.getPageSize(); float verticalMarginTotal = marginTopPt + marginBottomPt; float horizontalMarginTotal = marginLeftPt + marginRightPt; float imgMaxWidth = pageRect.getWidth() - horizontalMarginTotal - 2; float imgMaxHeight = pageRect.getHeight() - verticalMarginTotal - 2; float imgOrigWidth = img.getWidth(); float imgOrigHeight = img.getHeight(); if (imgOrigHeight > imgMaxHeight || imgOrigWidth > imgMaxWidth) { img.scaleToFit(imgMaxWidth, imgMaxHeight); } boolean addOK = addToDocument(img); if (!addOK) { System.err.println("** addToDocument(" + img.getUrl() + ") returned false"); } }
From source file:com.aryjr.nheengatu.pdf.PDFPageBreak.java
License:Open Source License
public PDFPageBreak(final PdfWriter writer, final Document document, final Tag headFirstPageTag, final Tag footFirstPageTag, final Tag headTag, final Tag footTag) throws DocumentException { this.headFirstPageTag = headFirstPageTag; this.footFirstPageTag = footFirstPageTag; this.headTag = headTag; this.footTag = footTag; final Rectangle page = document.getPageSize(); if (headTag != null) { final PDFTable pdft = createTable(writer, document, headTag); pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); headHeight = pdft.getTotalHeight(); }/*from w w w . j ava2 s. co m*/ if (footTag != null) { final PDFTable pdft = createTable(writer, document, footTag); pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); footHeight = pdft.getTotalHeight(); } if (headFirstPageTag != null) { final PDFTable pdft = createTable(writer, document, headFirstPageTag); pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); headFirstPageHeight = pdft.getTotalHeight(); } if (footFirstPageTag != null) { final PDFTable pdft = createTable(writer, document, footFirstPageTag); pdft.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); footFirstPageHeight = pdft.getTotalHeight(); } topMargin = document.topMargin(); bottomMargin = document.bottomMargin(); document.setMargins(document.leftMargin(), document.rightMargin(), topMargin + headFirstPageHeight, bottomMargin + footFirstPageHeight); }
From source file:com.aryjr.nheengatu.pdf.PDFPageBreak.java
License:Open Source License
@Override public void onEndPage(final PdfWriter writer, final Document document) { try {/*from w w w.j a v a 2s. c o m*/ final Rectangle page = document.getPageSize(); PDFTable head = null; PDFTable foot = null; if (writer.getPageNumber() == 1) { if (headFirstPageTag != null) head = createTable(writer, document, headFirstPageTag); if (footFirstPageTag != null) foot = createTable(writer, document, footFirstPageTag); } else { if (headTag != null) head = createTable(writer, document, headTag); if (footTag != null) foot = createTable(writer, document, footTag); } if (head != null) { head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - topMargin, writer.getDirectContent()); } if (foot != null) { foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); foot.writeSelectedRows(0, -1, document.leftMargin(), bottomMargin + foot.getTotalHeight(), writer.getDirectContent()); } } catch (final Exception e) { throw new ExceptionConverter(e); } document.setMargins(document.leftMargin(), document.rightMargin(), topMargin + headHeight, bottomMargin + footHeight); }