List of usage examples for com.lowagie.text Document newPage
public boolean newPage()
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 ww . j av a 2s .c o m 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.GeraRelatorioPDF.java
License:Open Source License
public static boolean geraRelatorio(File file) { TradGeraRelatorioPDF.carregaTexto(TokenLang.LANG); Document document = new Document(PageSize.A4); try {/*from www.j a v a 2s.c o m*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setPageEvent(new HeaderAndFooter()); document.open(); int linha = 0, j, tot_pg = ResumoDoRelatorio.getTotPage(); //calcula o total de htmls float tot_link = 0.0f; for (j = 1; j <= tot_pg; j++) { String conteudo = ResumoDoRelatorio.getPage(j); String arr[] = conteudo.split("\n"); tot_link += arr.length; } PainelStatusBar.showProgTarReq(); //loop por todas as pginas da paginacao for (j = 1; j <= tot_pg; j++) { String conteudo = ResumoDoRelatorio.getPage(j); String arr[] = conteudo.split("\n"); int tot = arr.length; int i; //loop por todos os links for (i = 0; i < tot; i++) { progresso = (linha++ / tot_link) * 100.0f; PainelStatusBar.setValueProgress((int) progresso); String arr2[] = arr[i].split("\t"); if (arr2.length == 8) { String strUrl = arr2[7];// URL /* int ap1 = Integer.parseInt(arr2[4]);// Aviso1 int ep1 = Integer.parseInt(arr2[1]);// Erro1 int ap2 = Integer.parseInt(arr2[5]);// Aviso2 int ep2 = Integer.parseInt(arr2[2]);// Erro2 int ap3 = Integer.parseInt(arr2[6]);// Aviso3 int ep3 = Integer.parseInt(arr2[3]);// Erro3 */ String myHash = arr2[0]; RelatorioDaUrl relatorio = new RelatorioDaUrl(); relatorio.recarregaArquivoRelatorioEmXml2(myHash); document.add(new Phrase("\n")); Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD); Chunk url = new Chunk(strUrl, font); Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL); p1.add(url); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p1); document.add(new Phrase("\n\n")); if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0 && relatorio.getErrosPrioridade3() <= 0) { Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS); p2.setAlignment(Paragraph.ALIGN_CENTER); document.add(p2); } else { if (relatorio.getErrosPrioridade1() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP1()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade2() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP2()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade3() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP3()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } document.newPage(); } } } } writer.flush(); document.close(); } catch (DocumentException de) { log.error(de.getMessage(), de); PainelStatusBar.hideProgTarReq(); return false; } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); PainelStatusBar.hideProgTarReq(); return false; } PainelStatusBar.hideProgTarReq(); return true; }
From source file:br.org.acessobrasil.silvinha.util.GeraRelatorioPDF.java
License:Open Source License
public static boolean geraRelatorio_bkp(File file, ResumoDoRelatorio resumo) { Document document = new Document(PageSize.A4); try {//ww w . j ava 2s.c o m PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setPageEvent(new HeaderAndFooter()); document.open(); ArrayList<RelatorioDaUrl> relatorios = resumo.getRelatorios(); loop: for (RelatorioDaUrl relatorio : relatorios) { document.add(new Phrase("\n")); Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD); Chunk url = new Chunk(relatorio.getUrl(), font); Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL); p1.add(url); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p1); document.add(new Phrase("\n\n")); if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0 && relatorio.getErrosPrioridade3() <= 0) { Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS); p2.setAlignment(Paragraph.ALIGN_CENTER); document.add(p2); continue loop; } if (relatorio.getErrosPrioridade1() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1_SEM_TAB, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP1()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade2() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2_SEM_TAB, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP2()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } if (relatorio.getErrosPrioridade3() > 0) { Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3_SEM_TAB, font); p1.setAlignment(Paragraph.ALIGN_LEFT); document.add(p); document.add(new Chunk("\n")); PdfPTable table = geraLista(relatorio.getListaErrosP3()); if (table != null) { document.add(table); } document.add(new Phrase("\n\n")); } document.newPage(); } writer.flush(); document.close(); } catch (DocumentException de) { log.error(de.getMessage(), de); return false; } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); return false; } return true; }
From source file:buckley.compile.Compiler.java
License:Apache License
public void compile(InputStream pdfTemplate, OutputStream output, final buckley.Document doc) { final Pdf pdf = new Pdf(pdfTemplate, output); try {/*from w w w .java 2 s . c o m*/ pdf.eachPage(new Pdf.PageHandler() { public void handlePage(int number, PdfReader reader, PdfWriter writer, Document document, PdfAcroForm form) { PdfContentByte content = writer.getDirectContent(); PdfImportedPage importedPage = writer.getImportedPage(reader, number); content.addTemplate(importedPage, 0.0f, 0.0f); if (doc.hasFields(number)) { Page page = doc.getPage(number); for (Field field : page.getFields()) { Rectangle fieldSize = fieldSizeFactory.build(field); ITextFieldFactory factory = fieldFactories.get(field.getClass()); BaseField iTextField = factory.build(writer, fieldSize, field.getName()); for (FieldAttributeModifier modifier : modifiers) { if (modifier.canModify(field)) { modifier.modify(iTextField, field, doc); } } try { writer.addAnnotation(factory.buildFormField(iTextField)); } catch (Exception e) { throw new RuntimeException(e); } } } document.newPage(); } }); } finally { pdf.close(); } }
From source file:bucks.GenerateChecks.java
License:Open Source License
void generate(HttpServletResponse res, Batch batch) { ServletOutputStream out = null;// w ww . java2 s .c om BuckConf conf = batch.getConf(); int start_seq = batch.getStart_seq_int(); int size = batch.getBatch_size_int(); String type = conf.getType_id(); String value = conf.getValue(); String filename = "market_bucks_" + Helper.getCurrentYear() + "_" + batch.getId() + ".pdf"; // we need to register these fonts // windows we use verdana // // for test purpose // /* start_seq = 612001; type="2"; value="5"; size = 6; */ try { Image image = Image.getInstance(imageUrl); // image.setWidthPercentage(20.0f); image.scalePercent(10f); Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11" // left right top bottom Document document = new Document(pageSize, 15, 15, 18, 12);// 1/4 inch ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); // int row = 1, page_no = 0; int page = 1; if (type.equals("1")) { // MB for (int jj = 0; jj < size; jj++) { generate_mb(document, start_seq + jj, value, image, writer); row++; if (row == 4 && (jj + 1) < size) { // to avoid empty page row = 1; page++; page_no = writer.getPageNumber(); if (page_no < page) { document.newPage(); } } } } else { // GC for (int jj = 0; jj < size; jj++) { generate_gc(document, start_seq + jj, value, image, writer); row++; if (row == 4 && (jj + 1) < size) { // to avoid empty page row = 1; page++; page_no = writer.getPageNumber(); // System.err.println(page+" "+page_no); if (page_no < page) { document.newPage(); } } } } // document.close(); writer.close(); res.setHeader("Expires", "0"); res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "public"); // // setting the content type res.setHeader("Content-Disposition", " attachment; filename=" + filename); res.setContentType("application/pdf"); // // the contentlength is needed for MSIE!!! res.setContentLength(baos.size()); // out = res.getOutputStream(); if (out != null) { baos.writeTo(out); } } catch (Exception ex) { System.err.println(ex); } }
From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java
License:Open Source License
/** * Outputs a PDF file report of the data in drs to the given * output stream.//from www. ja va 2 s . c o m * @throws SQLObjectException * @throws IllegalAccessException * @throws InstantiationException */ public void format(OutputStream out, List<ProfileResult> profileResults) throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException, IllegalAccessException, ClassNotFoundException { final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow final int mtop = 50; // margin at top of page (in points) final int mbot = 50; // margin at bottom of page (page numbers are below this) // final int pbot = 20; // padding between bottom margin and bottom of body text final int mlft = 50; // margin at left side of page final int mrgt = 50; // margin at right side of page final Rectangle pagesize = PageSize.LETTER.rotate(); final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot); final PdfWriter writer = PdfWriter.getInstance(document, out); final float fsize = 6f; // the font size to use in the table body final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); document.addTitle("Table Profiling Report"); document.addSubject("Tables: " + profileResults); document.addAuthor(System.getProperty("user.name")); document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION); document.open(); // vertical position where next element should start // (bottom is 0; top is pagesize.height()) float pos = pagesize.height() - mtop; final PdfContentByte cb = writer.getDirectContent(); final PdfTemplate nptemplate = cb.createTemplate(50, 50); writer.setPageEvent(new PdfPageEventHelper() { // prints the "page N of <template>" footer public void onEndPage(PdfWriter writer, Document document) { int pageN = writer.getPageNumber(); String text = "Page " + pageN + " of "; float len = bf.getWidthPoint(text, fsize - 2); cb.beginText(); cb.setFontAndSize(bf, fsize - 2); cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2); cb.showText(text); cb.endText(); cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2); } public void onCloseDocument(PdfWriter writer, Document document) { nptemplate.beginText(); nptemplate.setFontAndSize(bf, fsize - 2); nptemplate.showText(String.valueOf(writer.getPageNumber() - 1)); nptemplate.endText(); } }); document.add(new Paragraph("SQL Power Architect Profiling Report")); document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name"))); float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result Font f = new Font(bf, fsize); // This ddl generator is set to the appropriate ddl generator for the source database // every time we encounter a table profile result in the list. DDLGenerator ddlg = null; PdfPTable pdfTable = null; for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } double allowedTableSize = pagesize.width() - mrgt - mlft; double totalWidths = 0; for (int i = 0; i < headings.length; i++) { if (!columnsToTruncate.contains(headings[i])) { widths[i] += PIXELS_PER_BORDER; totalWidths += widths[i]; } } truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size()))) / columnsToTruncate.size(); logger.debug("Truncate length is " + truncateLength); widths = new float[totalColumn]; profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } for (int i = 0; i < headings.length; i++) { widths[i] += PIXELS_PER_BORDER; } // add the PdfPTables to the document; try to avoid orphan and widow rows pos = writer.getVerticalPosition(true) - fsize; logger.debug("Starting at pos=" + pos); boolean newPageInd = true; for (ProfileTableStructure profile : profiles) { pdfTable = profile.getMainTable(); pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft); pdfTable.setWidths(widths); resetHeaderWidths(profile, widths); int startrow = pdfTable.getHeaderRows(); int endrow = startrow; // current page will contain header+startrow..endrow /* no other rows in the table, just the header, and the header may * contain error message */ if (endrow == pdfTable.size()) { pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); continue; } while (endrow < pdfTable.size()) { // figure out how many body rows fit nicely on the page float endpos = pos - calcHeaderHeight(pdfTable); // y position of page number# = (mbot/2+fsize) while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2) && endrow < pdfTable.size()) { endpos -= pdfTable.getRowHeight(endrow); endrow++; } // adjust for orphan rows. Might create widows or make // endrow < startrow, which is handled later by deferring the table if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) { // page # maybe fall into table area, but usually that's column of // min value, usually that's enough space for both, or we should // disable page # on this page if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) { // short by 1 row.. just squeeze it in endrow = pdfTable.size(); } else { // more than 1 row remains: shorten this page so orphans aren't lonely endrow = pdfTable.size() - minRowsTogether; } } if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) { // this is the end of the table, or we have enough rows to bother printing pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb); startrow = endrow; newPageInd = false; } else { // not the end of the table and not enough rows to print out if (newPageInd) throw new IllegalStateException( "PDF Page is not large engouh to display " + minRowsTogether + " row(s)"); endrow = startrow; } // new page if necessary (that is, when we aren't finished the table yet) if (endrow != pdfTable.size()) { document.newPage(); pos = pagesize.height() - mtop; newPageInd = true; } } } document.close(); }
From source file:ch.gpb.elexis.cst.view.CstResultPart.java
License:Open Source License
private void makeActions(final Control viewer) { actionScreenshot = new Action() { public void run() { if (profile == null) { SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden"); return; }//w ww . j a v a2s. c o m GC gc = null; Image image = null; try { String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null); if (latestPath == null) { latestPath = System.getProperty("user.home"); } FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE); fd.setText("Save"); fd.setFilterPath(latestPath); String[] filterExt = { "*.png", "*.*" }; fd.setFilterExtensions(filterExt); fd.setFileName(CstService.generateFilename(patient)); String selected = fd.open(); if (selected == null) { return; } File selFile = new File(selected); CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH, selFile.getParentFile().getAbsolutePath()); //if (profile.getAnzeigeTyp().toLowerCase().equals("effektiv")) { if (profile.getAnzeigeTyp().toLowerCase().equals(CstProfile.ANZEIGETYP_EFFEKTIV)) { if (profile.getAusgabeRichtung()) { image = new Image(viewer.getDisplay(), 1123, viewer.getBounds().height); } else { image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height); } } else { image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height); } ImageLoader loader = new ImageLoader(); gc = new GC(image); viewer.print(gc); gc.dispose(); loader.data = new ImageData[] { image.getImageData() }; loader.save(selected, SWT.IMAGE_PNG); } catch (Exception e) { log.error("Error saving png: " + e.toString()); showMessage("Error while saving PNG", e.getMessage()); } finally { if (image != null) { image.dispose(); } if (gc != null) { gc.dispose(); } } } }; actionScreenshot.setText(Messages.Cst_Text_Save_as_png); actionScreenshot.setToolTipText(Messages.Cst_Text_Save_as_png); actionScreenshot.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ELEMENT)); actionScreenshot.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PNG_PATH)); // TODO: die pdf ausgabe ist eine ziemliche Baustelle - berarbeiten actionPdf = new Action() { public void run() { ////////////////////////// if (profile == null) { SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden"); return; } GC gc = null; Image image = null; try { String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null); if (latestPath == null) { latestPath = System.getProperty("user.home"); } FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE); fd.setText("Save"); fd.setFilterPath(latestPath); String[] filterExt = { "*.pdf", "*.*" }; fd.setFilterExtensions(filterExt); fd.setFileName(CstService.generateFilename(patient)); String selected = fd.open(); if (selected == null) { return; } File selFile = new File(selected); CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH, selFile.getParentFile().getAbsolutePath()); int printHeigth = 1123; int printWidth = 794; if (profile.getAusgabeRichtung()) { printHeigth = 794; printWidth = 1123; } // get the image from the viewport image = new Image(viewer.getDisplay(), printWidth, viewer.getBounds().height); ImageLoader loader = new ImageLoader(); gc = new GC(image); viewer.print(gc); gc.dispose(); // prepare title data //Date date = new Date(); //SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); Patient patient = Patient.load(profile.getKontaktId()); //String sTitle = "Gemeinschaftspraxis Brunnmatt Dr. Beat Knzi "; String sTitle; sTitle = profile.getOutputHeader() == null ? "No header configured!" : profile.getOutputHeader(); if (sTitle == null || sTitle.length() == 0) { sTitle = "No header configured!"; } sTitle = sTitle + " Datum: " + CstService.getReadableDateAndTime(); // get option (paging to A4/ in one piece) int pdfOutputOption = 0; boolean onePage = true; PdfOptionsDialog dialog = new PdfOptionsDialog(baseComposite.getShell()); dialog.create(); if (dialog.open() == Window.OK) { pdfOutputOption = dialog.getPdfOutputOption(); if (pdfOutputOption == PdfOptionsDialog.OPTION_ONE_PAGE) { onePage = true; } else { onePage = false; } } float docHeight = viewer.getBounds().height; docHeight = docHeight / 7.5f; float fontSize = 12f; if (docHeight < 360f) { docHeight = 360f; } BufferedImage bimage = ImageUtils.convertToAWT(image.getImageData()); // create an Itextt Image from AWT BufferedImage com.lowagie.text.Image itextImage = null; java.awt.Image awtImage = null; try { awtImage = Toolkit.getDefaultToolkit().createImage(bimage.getSource()); itextImage = com.lowagie.text.Image.getInstance(awtImage, null); } catch (Exception e) { log.error("Error on image loading: " + e.toString()); e.printStackTrace(); } // only for debugging //loader.data = new ImageData[] { image.getImageData() }; //loader.save("C:\\Users\\daniel\\tmp\\debug.png", SWT.IMAGE_PNG); Rectangle pagesize = new Rectangle(595f, itextImage.getHeight() * 0.75f); // is it a4 quer? if (profile.getAusgabeRichtung()) { pagesize = new Rectangle(842f, itextImage.getHeight() * 0.75f); } //System.out.println("pagesize: " + pagesize.toString()); Document document; if (onePage) { document = new Document(pagesize); } else { document = new Document(PageSize.A4); if (profile.getAusgabeRichtung()) { document = new Document(PageSize.A4.rotate()); } } document.addCreationDate(); try { // creation of the different writers PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(selected)); // various fonts BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true); BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true); BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", true); com.lowagie.text.Font fontHelv12 = new com.lowagie.text.Font(bf_helv, fontSize); com.lowagie.text.Font fontTimes = new com.lowagie.text.Font(bf_times, fontSize); fontTimes.setSize(fontSize); fontTimes.setStyle(com.lowagie.text.Font.ITALIC); Chunk chunkHeader = new Chunk(sTitle, FontFactory.getFont(FontFactory.HELVETICA, fontSize, com.lowagie.text.Font.NORMAL, new java.awt.Color(255, 0, 0))); com.lowagie.text.Phrase phraseHeader = new com.lowagie.text.Phrase(chunkHeader); // headers and footers must be added before the document // is opened Chunk chunkFooter = new Chunk("Seite: ", FontFactory.getFont(FontFactory.HELVETICA, fontSize, com.lowagie.text.Font.BOLD, new java.awt.Color(0, 0, 0))); Phrase phraseFooter = new Phrase(chunkFooter); phraseFooter.setFont(fontHelv12); HeaderFooter footer = new HeaderFooter(phraseFooter, true); footer.setBorder(Rectangle.NO_BORDER); footer.setAlignment(Element.ALIGN_CENTER); document.setFooter(footer); Phrase headerPhrase = new Phrase(sTitle); headerPhrase.setFont(fontTimes); HeaderFooter header = new HeaderFooter(phraseHeader, false); header.setBorder(Rectangle.BOTTOM); header.setBorderWidth(0.5f); header.setAlignment(Element.ALIGN_LEFT); document.setHeader(header); document.open(); //System.out.println("itext image w: " + itextImage.getWidth() + " h:" + itextImage.getHeight()); if (onePage) { int scale = 66; itextImage.scalePercent(scale); document.add(itextImage); } else { BufferedImage[] imageChunks = ImageUtils.splitImageByHeigth(bimage, printHeigth); for (int i = 0; i < imageChunks.length; i++) { com.lowagie.text.Image itextImage2 = com.lowagie.text.Image.getInstance( Toolkit.getDefaultToolkit().createImage(imageChunks[i].getSource()), null); // width becomes typically 523 (595 - 72) for a4Hoch or 770 (842 - 72) for A4Quer float imgWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(); float imgHeigth = itextImage.getHeight() * 0.75f; itextImage2.setAbsolutePosition(30, 20); int scale = 66; itextImage2.scalePercent(scale); document.add(itextImage2); document.newPage(); } } // we're done! document.close(); /////////////////////////////// } catch (Exception ex) { log.error(ex.getMessage()); showMessage("Error while generating PDF", ex.getMessage()); } } finally { if (image != null) { image.dispose(); } if (gc != null) { gc.dispose(); } /* image.dispose(); gc.dispose(); */ } } }; actionPdf.setText(Messages.Cst_Text_Save_as_pdf); actionPdf.setToolTipText(Messages.Cst_Text_Save_as_pdf); /* * actionPdf.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages() * .getImageDescriptor(ISharedImages.IMG_OBJ_FILE)); */ actionPdf.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PDF_PATH)); }
From source file:ch.gpb.elexis.kgexporter.pdf.HeaderFooterPageEvent.java
License:Open Source License
@Override public void onParagraph(PdfWriter paramPdfWriter, Document paramDocument, float paramFloat) { //super.onParagraph(paramPdfWriter, paramDocument, paramFloat); //System.out.println("paramFloat:" + paramFloat); if (paramFloat < 200f) { paramDocument.newPage(); }//from w w w .ja v a 2 s . com }
From source file:clases.unirPdf.java
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) { Document document = new Document(); try {/*from w ww . j a v a 2 s. c o m*/ List<InputStream> pdfs = streamOfPDFFiles; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { Rectangle rectangle = pdfReader.getPageSizeWithRotation(1); document.setPageSize(rectangle); document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); switch (rectangle.getRotation()) { case 0: cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); break; case 90: cb.addTemplate(page, 0, -1f, 1f, 0, 0, pdfReader.getPageSizeWithRotation(1).getHeight()); break; case 180: cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0); break; case 270: cb.addTemplate(page, 0, 1.0F, -1.0F, 0, pdfReader.getPageSizeWithRotation(1).getWidth(), 0); break; default: break; } if (paginate) { cb.beginText(); cb.getPdfDocument().getPageSize(); cb.endText(); } } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
From source file:classroom.filmfestival_b.Movies09.java
@SuppressWarnings("unchecked") public static void main(String[] args) { // step 1//from w ww. ja va 2 s .c o m Document document = new Document(); try { // step 2 OutputStream os = new FileOutputStream(RESULT); PdfWriter writer = PdfWriter.getInstance(document, os); // step 3 document.open(); // step 4 Session session = (Session) MySessionFactory.currentSession(); Query q = session.createQuery("from FilmTitle order by title"); java.util.List<FilmTitle> results = q.list(); ColumnText column = new ColumnText(writer.getDirectContent()); column.setSimpleColumn(document.left(), document.bottom(), document.right(), document.top()); float pos; int status; File f; Image img; Paragraph p; Chunk c; Font bold = new Font(Font.HELVETICA, 12, Font.BOLD); Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC); for (FilmTitle movie : results) { f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg"); if (f.exists()) { img = Image.getInstance(f.getPath()); img.setWidthPercentage(0); img.scaleToFit(72, 144); } else { img = null; } p = new Paragraph(20); c = new Chunk(movie.getTitle(), bold); c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId()); p.add(c); c = new Chunk(" (" + movie.getYear() + ") ", italic); p.add(c); c = new Chunk("IMDB"); c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb()); p.add(c); Set<DirectorName> directors = movie.getDirectorNames(); List list = new List(); for (DirectorName director : directors) { list.add(director.getName()); } if (img != null) column.addElement(img); column.addElement(p); column.addElement(list); pos = column.getYLine(); status = column.go(true); if (ColumnText.hasMoreText(status)) { document.newPage(); column.setText(null); column.setYLine(document.top()); } else { column.setYLine(pos); } if (img != null) column.addElement(img); column.addElement(p); column.addElement(list); column.addElement(Chunk.NEWLINE); column.go(); } // step 5 document.close(); } catch (IOException e) { LOGGER.error("IOException: ", e); } catch (DocumentException e) { LOGGER.error("DocumentException: ", e); } }