List of usage examples for com.itextpdf.text Document newPage
public boolean newPage()
From source file:Export.SeguroViagem.java
public String criarDoc(ViagemBean vb, String numCriente, String user, String arquivo, Contrato c) { try {/*from w ww .j av a 2s.c o m*/ PdfPTable pTablePrincaipal; // PdfPTable pTableSegu1; PdfPTable pTableSegu2; SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh'.'mm'.'ss"); SimpleDateFormat sdfPot = new SimpleDateFormat("dd/MM/yyyy"); Font fontCorpoN = FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED, 7.9f); Font fontCorpo = FontFactory.getFont(Fontes.FONT, BaseFont.WINANSI, BaseFont.EMBEDDED, 7.9f); // PdfPTable pTableLinha = new PdfPTable(1); // pTableLinha.setWidthPercentage(95); // PdfPCell linha= new PdfPCell(new Phrase(" ")); // // linha.setBorderWidthTop(0.5f); // linha.setBorderWidthBottom(0); // linha.setBorderWidthLeft(0); // linha.setBorderWidthRight(0); // pTableLinha.addCell(linha); Document documento = new Document(); documento.setPageSize(PageSize.A4); documento.setMargins(20f, 20f, 138f, 5f); File ff = new File(arquivo + "/" + user + "/Seguro Viagem/"); ff.mkdirs(); String Ddata = sdf.format(new Date()); ff = new File(ff.getAbsoluteFile() + "/" + "Doc Seguro Viagem " + Ddata + ".pdf"); reString = "../Documentos/" + user + "/Seguro Viagem/" + "Doc Seguro Viagem " + Ddata + ".pdf"; outputStraem = new FileOutputStream(ff); PdfWriter writer = PdfWriter.getInstance(documento, outputStraem); if (MarcaDAgua.isSimulation) { MarcaDAgua.SimulacaoVertical v = new MarcaDAgua.SimulacaoVertical(); writer.setPageEvent(v); } if (MarcaDAgua.isCanceled) { MarcaDAgua.AnulacaoVertical v = new MarcaDAgua.AnulacaoVertical(); writer.setPageEvent(v); } documento.open(); int total = vb.getInfoPessoaSegurada().size(); for (int i = 0; i < total; i++) { pTablePrincaipal = new PdfPTable(1); pTablePrincaipal.setWidthPercentage(98f); // pTableSegu1 = new PdfPTable(1); // pTableSegu1.setWidthPercentage(95); pTableSegu2 = new PdfPTable(new float[] { 55f, 45f }); pTableSegu2.setWidthPercentage(100f); // PdfPCell cellTitulo= new PdfPCell(new Phrase("Lista Pessoas Seguradas",fontCabecalhoN)); // cellTitulo.setBorder(0); PdfPCell cellNull = new PdfPCell(new Phrase(" ", fontCorpo)); cellNull.setBorder(0); // if(((i)%6)==0) // { // pTableSegu1.addCell(cellTitulo); // pTableSegu1.addCell(cellNull); // } // Paragraph pCl = new Paragraph(); pCl.add(new Phrase("Nome do Segurado: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getNomePessoaSegurada().toUpperCase(), fontCorpoN)); PdfPCell cellNome = new PdfPCell(pCl); cellNome.setColspan(2); cellNome.setBorder(0); pTableSegu2.addCell(cellNome); // PdfPCell cellNum= new PdfPCell(new Phrase(""+(i+1),fontCorpo)); // cellNum.setBorder(0); // cellNum.setHorizontalAlignment(Element.ALIGN_RIGHT); // pTableSegu2.addCell(cellNum); pCl = new Paragraph(); pCl.add(new Phrase("Endereo: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getEndereco().toUpperCase(), fontCorpoN)); PdfPCell cellEndereco = new PdfPCell(pCl); cellEndereco.setBorder(0); pTableSegu2.addCell(cellEndereco); pTableSegu2.addCell(cellNull); pCl = new Paragraph(); pCl.add(new Phrase("Data e Local Nascimento: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getDataNascFormatada(), fontCorpoN)); pCl.add(new Phrase(" em ", fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getLocalNascimento(), fontCorpoN)); PdfPCell cellNascDaNascloc = new PdfPCell(pCl); cellNascDaNascloc.setBorder(0); pCl = new Paragraph(); pCl.add(new Phrase("Sexo: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getSexo(), fontCorpoN)); pCl.add(new Phrase(" Tel.N ", fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getTelefone(), fontCorpoN)); PdfPCell cellSexo = new PdfPCell(pCl); cellSexo.setBorder(0); pTableSegu2.addCell(cellNascDaNascloc); pTableSegu2.addCell(cellSexo); pCl = new Paragraph(); pCl.add(new Phrase("Apolice: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getNumApolice(), fontCorpoN)); PdfPCell cellApolice = new PdfPCell(pCl); cellApolice.setBorder(0); pCl = new Paragraph(); pCl.add(new Phrase("Cliente: ".toUpperCase(), fontCorpo)); String[] codCliente = vb.getInfoPessoaSegurada().get(i).getNumApolice().split("/"); pCl.add(new Phrase(((codCliente.length == 2) ? "TIN " + codCliente[1] : "TIN "), fontCorpoN)); PdfPCell cellCliente = new PdfPCell(pCl); cellCliente.setBorder(0); pTableSegu2.addCell(cellApolice); pTableSegu2.addCell(cellCliente); pCl = new Paragraph(); pCl.add(new Phrase("Durao: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getNumDias() + " DIAS", fontCorpoN)); PdfPCell cellDuracao = new PdfPCell(pCl); cellDuracao.setBorder(0); pCl = new Paragraph(); pCl.add(new Phrase("Perodo: de ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(sdfPot.format(vb.getInfoPessoaSegurada().get(i).getDataInicio()), fontCorpoN)); pCl.add(new Phrase(" ", fontCorpo)); pCl.add(new Phrase(((vb.getInfoPessoaSegurada().get(i).getDataFim() != null) ? sdfPot.format(vb.getInfoPessoaSegurada().get(i).getDataFim()) : " "), fontCorpoN)); PdfPCell cellPeriodo = new PdfPCell(pCl); cellPeriodo.setBorder(0); pTableSegu2.addCell(cellDuracao); pTableSegu2.addCell(cellPeriodo); pCl = new Paragraph(); pCl.add(new Phrase("Data de Emisso: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(sdfPot.format(c.getDataContrato()), fontCorpoN)); PdfPCell cellDataEmissao = new PdfPCell(pCl); cellDataEmissao.setBorder(0); pCl = new Paragraph(); pCl.add(new Phrase("Destino: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase( ClienteDao.paisesSelected(vb.getInfoPessoaSegurada().get(i).getPaisDestino().toUpperCase()) + " ", fontCorpoN)); pCl.add(new Phrase("N de Pessoas: ", fontCorpo)); pCl.add(new Phrase((i + 1) + "", fontCorpoN)); PdfPCell cellDestino = new PdfPCell(pCl); cellDestino.setBorder(0); pTableSegu2.addCell(cellDataEmissao); pTableSegu2.addCell(cellDestino); pCl = new Paragraph(); pCl.add(new Phrase("Meio de Identificao: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase( ((vb.getInfoPessoaSegurada().get(i).getTipoDoc().toUpperCase().equals("PASSAPORTE")) ? "PASS" : (vb.getInfoPessoaSegurada().get(i).getTipoDoc().toUpperCase() .equals("BILHETE IDENTIDADE") ? "BI" : vb.getInfoPessoaSegurada().get(i).getTipoDoc().toUpperCase())), fontCorpoN)); pCl.add(new Phrase(" N ", fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getNumDoc(), fontCorpoN)); PdfPCell cellEmiDocNum = new PdfPCell(pCl); cellEmiDocNum.setBorder(0); pCl = new Paragraph(); pCl.add(new Phrase("Emitido em: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getLocalEmissao().toUpperCase() + " ", fontCorpoN)); pCl.add(new Phrase("em ", fontCorpo)); pCl.add(new Phrase(vb.getInfoPessoaSegurada().get(i).getDataEmissaoFormatada(), fontCorpoN)); PdfPCell cellEmiDoc = new PdfPCell(pCl); cellEmiDoc.setBorder(0); pTableSegu2.addCell(cellEmiDocNum); pTableSegu2.addCell(cellEmiDoc); pCl = new Paragraph(); pCl.add(new Phrase("Outras Informaes: ".toUpperCase(), fontCorpo)); pCl.add(new Phrase( ((vb.getInfoPessoaSegurada().get(i).getOutrasInformacoes() == null) ? " " : vb.getInfoPessoaSegurada().get(i).getOutrasInformacoes().toUpperCase()), fontCorpoN)); PdfPCell cellOutraInf = new PdfPCell(pCl); cellOutraInf.setColspan(2); cellOutraInf.setBorder(0); pTableSegu2.addCell(cellOutraInf); // PdfPCell cellSegui1 = new PdfPCell(); // cellSegui1.addElement(pTableSegu1); // cellSegui1.setBorder(0); PdfPCell cellSegui2 = new PdfPCell(); cellSegui2.addElement(pTableSegu2); cellSegui2.setBorder(0); // PdfPCell cellSeguiT = new PdfPCell(); // cellSeguiT.addElement(pTableLinha); // cellSeguiT.setBorder(0); // pTablePrincaipal.addCell(cellSegui1); pTablePrincaipal.addCell(cellSegui2); // if((i+1)<total&&((i+1)%6)!=0) // pTablePrincaipal.addCell(cellSeguiT); // documento.add(pTablePrincaipal); // // System.err.println((((i+1)%6)==0)+" "+(i+1)); if ((i + 1) != total) { documento.newPage(); } } documento.close(); return reString; } catch (DocumentException | IOException ex) { Logger.getLogger(SeguroViagem.class.getName()).log(Level.SEVERE, null, ex); return reString; } }
From source file:ExternalNonFormClasses.PDFEnator.java
public void createPDF() { try {/*w w w . jav a2 s. c o m*/ Rectangle one = new Rectangle(PageSize.LETTER); Document doc = new Document(one); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(getDirectory() + "\\" + data_title + ".pdf")); //doc.setMargins(1, 1, 1, 1); doc.open(); PdfContentByte canvas = writer.getDirectContent(); Font font = new Font(Font.FontFamily.TIMES_ROMAN, 11); x = one.getWidth(); y = one.getHeight(); tableX = (x / 2) - 235; tableY = y - 180; getHeader(); Paragraph para = new Paragraph("Province of " + formHeaderValues[0], font); para.setAlignment(Element.ALIGN_CENTER); doc.add(para); Paragraph para2 = new Paragraph("City/Municipality of " + formHeaderValues[1], font); para2.setAlignment(Element.ALIGN_CENTER); doc.add(para2); Paragraph para3 = new Paragraph("Barangay " + formHeaderValues[2], font); para3.setAlignment(Element.ALIGN_CENTER); doc.add(para3); doc.add(Chunk.NEWLINE); doc.add(Chunk.NEWLINE); Paragraph para4 = new Paragraph(data_title, font); para4.setAlignment(Element.ALIGN_CENTER); doc.add(para4); PdfPTable pdftable; pdftable = writeHeaders(font); //pdftable.writeSelectedRows(0, -1, (x / 2) - 235, y - 180, canvas); int counter = 1, rowCounter = 0, columnCounter = 0; int yIncrementor = 16; boolean test = true; while (counter <= this.totalDataSize) { //System.out.println("data#: " + counter + "@ (" + rowCounter + "," + (columnCounter) + ") = " + this.table.getValueAt(rowCounter, columnCounter).toString()); PdfPCell cell1 = new PdfPCell( new Paragraph(this.table.getValueAt(rowCounter, columnCounter++).toString(), font)); cell1.setPaddingBottom(5); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); pdftable.addCell(cell1); if (counter > 0 && (counter % column) == 0) { //if there are 4 columns //pdftable.writeSelectedRows(0, -1, (x / 2) - 235, (y - 180) - yIncrementor, canvas); //print row of 4 columns yIncrementor += 16; //move to next row coordinate, so y coordinate plus plus rowCounter++; //move to next row columnCounter = 0; //back to start column boolean newPage = false; if ((tableY - ((yIncrementor - 16) + 80)) <= 72) { //if it exceeds 1 inch in footer, new page // System.out.println("(" + tableY + "-((" + yIncrementor + "-16)+" + 16 + "))"); // System.out.println("Nanobra? YES; " + (tableY - ((yIncrementor - 16) + 16))); newPage = true; } else if ((tableY - (yIncrementor + 80)) <= 72) { // System.out.println("(" + tableY + "-(" + yIncrementor + "+" + 16 + "))"); // System.out.println("Nanobra? YES; " + (tableY - (yIncrementor + 16))); newPage = true; } if (newPage) { pdftable.completeRow(); pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas); //print the data for the current page doc.newPage(); //create new page pdftable = writeHeaders(font); //write headers to new page yIncrementor = 16; //restore default } } // if (counter == this.totalDataSize) { //para lng mudouble ang data // if (test) { // test = false; // counter = 0; // rowCounter = 0; // columnCounter = 0; // } // } else if (counter == this.totalDataSize) { // if (!test) { // break; // } // } counter++; } pdftable.completeRow(); pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas); doc.close(); } catch (DocumentException | FileNotFoundException ex) { Logger.getLogger(PDFEnator.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ExternalNonFormClasses.PDFEnator.java
public void createProfilePDF(String id, ArrayList<String> data) { this.data_title = "Citizen Profile"; this.table = null; this.caller = 4; this.row = 17; this.column = 2; this.personID = id; this.totalDataSize = row * column; tableHeaderData = new ArrayList<>(); tableHeaderData.add("Label"); tableHeaderData.add("Information"); ArrayList<String> dataAll = data; try {/*from www . jav a 2s. com*/ getHeader(); Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(getDirectory() + "\\" + data_title + ".pdf")); Rectangle one = new Rectangle(PageSize.LETTER); doc.setPageSize(one); //doc.setMargins(1, 1, 1, 1); doc.open(); PdfContentByte canvas = writer.getDirectContent(); Font font = new Font(Font.FontFamily.TIMES_ROMAN, 11); x = one.getWidth(); y = one.getHeight(); tableX = (x / 2) - 235; tableY = y - 180; Paragraph para = new Paragraph("Province of " + formHeaderValues[0], font); para.setAlignment(Element.ALIGN_CENTER); doc.add(para); Paragraph para2 = new Paragraph("City/Municipality of " + formHeaderValues[1], font); para2.setAlignment(Element.ALIGN_CENTER); doc.add(para2); Paragraph para3 = new Paragraph("Barangay " + formHeaderValues[2], font); para3.setAlignment(Element.ALIGN_CENTER); doc.add(para3); Paragraph para4 = new Paragraph(data_title, font); para4.setAlignment(Element.ALIGN_CENTER); doc.add(para4); PdfPTable pdftable; pdftable = writeHeaders(font); int counter = 1, rowCounter = 0, columnCounter = 0; int yIncrementor = 16; String label = null, value = null; System.out.println(dataAll.size()); while (counter <= this.row) { switch (counter - 1) { case 0: label = "Citizen ID"; value = id; break; case 1: label = "Last Name"; value = dataAll.get(counter - 2); break; case 2: label = "First Name"; value = dataAll.get(counter - 2); break; case 3: label = "Middle Name"; value = dataAll.get(counter - 2); break; case 4: label = "Name Suffix"; value = dataAll.get(counter - 2); break; case 5: label = "Date of Birth"; value = dataAll.get(counter - 2); break; case 6: label = "Gender"; value = dataAll.get(counter - 2); break; case 7: label = "Address"; value = dataAll.get(counter - 2); break; case 8: label = "Age"; value = dataAll.get(counter - 2); break; case 9: label = "Place of Birth"; value = dataAll.get(counter - 2); break; case 10: label = "Civil Status"; value = dataAll.get(counter - 2); break; case 11: label = "Contact"; value = dataAll.get(counter - 2); break; case 12: label = "Zip Code"; value = dataAll.get(counter - 2); break; case 13: label = "Precinct Number"; value = dataAll.get(counter - 2); break; case 14: label = "Occupation"; value = dataAll.get(counter - 2); break; case 15: label = "Email Address"; value = dataAll.get(counter - 2); break; case 16: label = "Religion"; value = dataAll.get(counter - 2); break; } if (value.length() <= 0) { value = "N/A"; } System.out.println(label + ": " + value); PdfPCell cell1 = new PdfPCell(new Paragraph(label, font)); cell1.setPaddingBottom(5); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); pdftable.addCell(cell1); PdfPCell cell2 = new PdfPCell(new Paragraph(value, font)); cell2.setPaddingBottom(5); cell2.setHorizontalAlignment(Element.ALIGN_LEFT); pdftable.addCell(cell2); if (counter > 0 && (counter % column) == 0) { //if there are 4 columns yIncrementor += 16; //move to next row coordinate, so y coordinate plus plus rowCounter++; //move to next row columnCounter = 0; //back to start column boolean newPage = false; if ((tableY - ((yIncrementor - 16) + 80)) <= 72 || (tableY - (yIncrementor + 80)) <= 72) { //if it exceeds 1 inch in footer, new page newPage = true; } if (newPage) { pdftable.completeRow(); pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas); //print the data for the current page doc.newPage(); //create new page pdftable = writeHeaders(font); //write headers to new page yIncrementor = 16; //restore default } } counter++; } pdftable.completeRow(); pdftable.writeSelectedRows(0, -1, tableX, tableY, canvas); doc.close(); } catch (DocumentException | FileNotFoundException ex) { Logger.getLogger(PDFEnator.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:eyeofthetiger.utils.PDFDossardGenerator.java
public void createPdf(List<Participant> participants, OutputStream out) throws IOException, DocumentException { sortParticipants(participants);/*from w w w . ja va2 s. co m*/ Document document = new Document(PageSize.A4.rotate()); float margin = CentimeterToUserSpace(marginCm); document.setMargins(margin, margin, margin, margin); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfReader pdfBackgroundReader = null; PdfImportedPage backgroundPage = null; if (pdfBackground != null && (new File(pdfBackground)).exists() && (new File(pdfBackground)).isFile()) { pdfBackgroundReader = new PdfReader(pdfBackground); backgroundPage = writer.getImportedPage(pdfBackgroundReader, 1); } float documentTop = document.top(); float documentBottom = document.bottom(); float documentHeight = documentTop - documentBottom; float left = document.left(); float right = document.right(); float width = right - left; float height = documentTop - documentBottom; //cb.rectangle(left, documentBottom, width, documentHeight); //cb.stroke(); boolean logoLeftExist = (new File(logoLeft)).exists() && (new File(logoLeft)).isFile(); boolean logoRightExist = (new File(logoRight)).exists() && (new File(logoRight)).isFile(); float imgLeftRight = left; float imgLeftBottom = documentTop; float imgRightLeft = right; float imgRighBottom = documentTop; Image imgLeft = null; Image imgRight = null; if (exportLogos) { if (logoLeftExist) { imgLeft = Image.getInstance(logoLeft); float h = imgLeft.getHeight(); float w = imgLeft.getWidth(); float nw = width * logoLeftWidth; float nh = (h / w) * nw; imgLeft.scaleAbsolute(nw, nh); //img.scaleAbsoluteHeight(img.getScaledWidth() / xyRatio); imgLeft.setAbsolutePosition(left, documentTop - imgLeft.getScaledHeight()); //cb.addImage(img); imgLeftRight = imgLeft.getAbsoluteX() + imgLeft.getScaledWidth(); imgLeftBottom = imgLeft.getAbsoluteY(); } if (logoRightExist) { imgRight = Image.getInstance(logoRight); float h = imgRight.getHeight(); float w = imgRight.getWidth(); float nw = width * logoRightWidth; float nh = (h / w) * nw; imgRight.scaleAbsolute(nw, nh); imgRight.setAbsolutePosition(right - imgRight.getScaledWidth(), documentTop - imgRight.getScaledHeight()); //cb.addImage(imgRight); imgRightLeft = imgRight.getAbsoluteX(); imgRighBottom = imgRight.getAbsoluteY(); } } float nameHeightPercent = 0.35f; float groupHeightPercent = 0.25f; float nameTop = documentTop; float nameBottom = nameTop; if (exportName) { nameBottom = nameTop - (documentHeight * nameHeightPercent); } float groupeTop = nameBottom; float groupeBottom = nameBottom; if (exportGroup) { groupeBottom = groupeTop - (documentHeight * groupHeightPercent); } float barcodeTop = groupeBottom; float barcodeBottom = documentBottom; ColumnText columnText; for (Participant participant : participants) { if (backgroundPage != null) { //cb.addTemplate(backgroundPage, 1f, 0, 0, 1, 0, 0); //TODO cb.addTemplate(backgroundPage, 0, 0); } float nameFontSize = 65f; float groupFontSize = 45f; float renseignementFontSize = 35f; if (imgLeft != null) { cb.addImage(imgLeft); } if (imgRight != null) { cb.addImage(imgRight); } if (exportName) { columnText = new ColumnText(cb); columnText.setAlignment(Rectangle.ALIGN_CENTER); if (imgLeftRight != -1 && imgLeftBottom != -1) { float[] leftBorder = null; if (imgLeftBottom < nameBottom) { leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, nameBottom, left, nameBottom }; } else { leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, imgLeftBottom, left, imgLeftBottom, left, nameBottom }; } float[] rightBorder = null; if (imgRighBottom < nameBottom) { rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, nameBottom, right, nameBottom }; } else { rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, imgRighBottom, right, imgRighBottom, right, nameBottom }; } columnText.setColumns(leftBorder, rightBorder); } else { columnText.setSimpleColumn(left, nameTop, right, nameBottom); } //cb.rectangle(left, nameBottom, width, (nameTop - nameBottom)); //cb.stroke(); columnText.setExtraParagraphSpace(0f); columnText.setAdjustFirstLine(false); columnText.setIndent(0); String txt = participant.getNom().toUpperCase() + " " + participant.getPrenom(); float previousPos = columnText.getYLine(); columnText.setLeading(nameFontSize); columnText.setText(createCleanPhrase(txt, nameFontSize, true)); while (nameFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) { nameFontSize = nameFontSize - 0.5f; columnText.setLeading(nameFontSize); columnText.setText(createCleanPhrase(txt, nameFontSize, true)); columnText.setYLine(previousPos); } columnText.setLeading(nameFontSize); columnText.setText(createCleanPhrase(txt, nameFontSize, true)); columnText.setYLine(previousPos); columnText.go(false); } if (exportGroup) { columnText = new ColumnText(cb); columnText.setAlignment(Rectangle.ALIGN_CENTER); columnText.setSimpleColumn(document.left(), groupeTop, document.right(), groupeBottom); float groupeHeight = groupeTop - groupeBottom; //cb.rectangle(document.left(), groupeTop - groupeHeight, document.right() - document.left(), groupeHeight); //cb.stroke(); columnText.setExtraParagraphSpace(0f); columnText.setAdjustFirstLine(false); columnText.setIndent(0); columnText.setFollowingIndent(0); String txt1 = participant.getGroupe(); String txt2 = exportRenseignement ? "\n" + participant.getRenseignements() : null; float previousPos = columnText.getYLine(); columnText.setText(null); columnText.setLeading(groupFontSize); columnText.addText(createCleanPhrase(txt1, groupFontSize, true)); columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false)); while (groupFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) { groupFontSize = groupFontSize - 0.5f; renseignementFontSize = renseignementFontSize - 0.5f; columnText.setText(null); columnText.setLeading(groupFontSize); columnText.addText(createCleanPhrase(txt1, groupFontSize, true)); columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false)); columnText.setYLine(previousPos); } columnText.setText(null); columnText.setLeading(groupFontSize); columnText.addText(createCleanPhrase(txt1, groupFontSize, true)); columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false)); columnText.setYLine(previousPos); columnText.go(false); } { columnText = new ColumnText(cb); float topMargin = 12f; columnText.setSimpleColumn(left, barcodeTop - topMargin, right, barcodeBottom); float barcodeHeight = (barcodeTop - topMargin) - barcodeBottom; //cb.rectangle(left, barcodeTop - barcodeHeight, width, barcodeHeight); //cb.stroke(); columnText.setExtraParagraphSpace(0f); columnText.setAdjustFirstLine(false); columnText.setIndent(0); float previousPos = columnText.getYLine(); columnText.setText(null); columnText.addElement(createCleanBarcode(cb, participant.getNumero(), width, barcodeHeight)); columnText.go(false); } document.newPage(); } document.close(); if (pdfBackgroundReader != null) { pdfBackgroundReader.close(); } }
From source file:fll.web.playoff.ScoresheetGenerator.java
License:Open Source License
public void writeFile(final OutputStream out, final boolean orientationIsPortrait) throws DocumentException { // This creates our new PDF document and declares its orientation Document pdfDoc; if (orientationIsPortrait) { pdfDoc = new Document(PageSize.LETTER); // portrait } else {/*from ww w . ja v a 2 s . com*/ pdfDoc = new Document(PageSize.LETTER.rotate()); // landscape } PdfWriter.getInstance(pdfDoc, out); // Measurements are always in points (72 per inch) // This sets up 1/2 inch margins side margins and 0.35in top and bottom // margins pdfDoc.setMargins(0.5f * POINTS_PER_INCH, 0.5f * POINTS_PER_INCH, 0.35f * POINTS_PER_INCH, 0.35f * POINTS_PER_INCH); pdfDoc.open(); // Header cell with challenge title to add to both scoresheets final Paragraph titleParagraph = new Paragraph(); final Chunk titleChunk = new Chunk(m_pageTitle, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 14, Font.NORMAL, BaseColor.WHITE)); titleParagraph.setAlignment(Element.ALIGN_CENTER); titleParagraph.add(titleChunk); titleParagraph.add(Chunk.NEWLINE); final Chunk swVersionChunk = new Chunk("SW version: " + Version.getVersion(), FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, BaseColor.WHITE)); titleParagraph.add(swVersionChunk); if (null != m_revision) { final Chunk revisionChunk = new Chunk(" Descriptor revision: " + m_revision, FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, BaseColor.WHITE)); titleParagraph.add(revisionChunk); } final PdfPCell head = new PdfPCell(); head.setColspan(2); head.setBorder(1); head.setPaddingTop(0); head.setPaddingBottom(3); head.setBackgroundColor(new BaseColor(64, 64, 64)); head.setVerticalAlignment(Element.ALIGN_TOP); head.addElement(titleParagraph); // Cells for score field, and 2nd check initials final Phrase des = new Phrase("Data Entry Score _______", ARIAL_8PT_NORMAL); final PdfPCell desC = new PdfPCell(des); desC.setBorder(0); desC.setPaddingTop(9); desC.setPaddingRight(36); desC.setHorizontalAlignment(Element.ALIGN_RIGHT); final Phrase sci = new Phrase("2nd Check Initials _______", ARIAL_8PT_NORMAL); final PdfPCell sciC = new PdfPCell(sci); sciC.setBorder(0); sciC.setPaddingTop(9); sciC.setPaddingRight(36); sciC.setHorizontalAlignment(Element.ALIGN_RIGHT); // Create a table with a grid cell for each scoresheet on the page PdfPTable wholePage = getTableForPage(orientationIsPortrait); wholePage.setWidthPercentage(100); for (int i = 0; i < m_numSheets; i++) { if (i > 0 && (orientationIsPortrait || (i % 2) == 0)) { pdfDoc.newPage(); wholePage = getTableForPage(orientationIsPortrait); wholePage.setWidthPercentage(100); } // This table is a single score sheet final PdfPTable scoreSheet = new PdfPTable(2); // scoreSheet.getDefaultCell().setBorder(Rectangle.LEFT | Rectangle.BOTTOM // | Rectangle.RIGHT | Rectangle.TOP); //FIXME DEBUG should be NO_BORDER scoreSheet.getDefaultCell().setBorder(Rectangle.NO_BORDER); scoreSheet.getDefaultCell().setPaddingRight(1); scoreSheet.getDefaultCell().setPaddingLeft(0); scoreSheet.addCell(head); final PdfPTable teamInfo = new PdfPTable(7); teamInfo.setWidthPercentage(100); teamInfo.setWidths(new float[] { 1f, 1f, 1f, 1f, 1f, 1f, .9f }); // Time label cell final Paragraph timeP = new Paragraph("Time:", ARIAL_10PT_NORMAL); timeP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell timeLc = new PdfPCell(scoreSheet.getDefaultCell()); timeLc.addElement(timeP); teamInfo.addCell(timeLc); // Time value cell final Paragraph timeV = new Paragraph(null == m_time[i] ? SHORT_BLANK : m_time[i], COURIER_10PT_NORMAL); final PdfPCell timeVc = new PdfPCell(scoreSheet.getDefaultCell()); timeVc.addElement(timeV); teamInfo.addCell(timeVc); // Table label cell final Paragraph tblP = new Paragraph("Table:", ARIAL_10PT_NORMAL); tblP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell tblLc = new PdfPCell(scoreSheet.getDefaultCell()); tblLc.addElement(tblP); teamInfo.addCell(tblLc); // Table value cell final Paragraph tblV = new Paragraph(m_table[i], COURIER_10PT_NORMAL); final PdfPCell tblVc = new PdfPCell(scoreSheet.getDefaultCell()); tblVc.addElement(tblV); teamInfo.addCell(tblVc); // Round number label cell final Paragraph rndP = new Paragraph("Round:", ARIAL_10PT_NORMAL); rndP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell rndlc = new PdfPCell(scoreSheet.getDefaultCell()); rndlc.addElement(rndP); teamInfo.addCell(rndlc); // Round number value cell final Paragraph rndV = new Paragraph(m_round[i], COURIER_10PT_NORMAL); final PdfPCell rndVc = new PdfPCell(scoreSheet.getDefaultCell()); // rndVc.setColspan(2); rndVc.addElement(rndV); teamInfo.addCell(rndVc); final PdfPCell temp1 = new PdfPCell(scoreSheet.getDefaultCell()); // temp1.setColspan(2); temp1.addElement(new Paragraph("Judge ____", ARIAL_8PT_NORMAL)); teamInfo.addCell(temp1); // Team number label cell final Paragraph nbrP = new Paragraph("Team #:", ARIAL_10PT_NORMAL); nbrP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell nbrlc = new PdfPCell(scoreSheet.getDefaultCell()); nbrlc.addElement(nbrP); teamInfo.addCell(nbrlc); // Team number value cell final Paragraph nbrV = new Paragraph(null == m_number[i] ? SHORT_BLANK : String.valueOf(m_number[i]), COURIER_10PT_NORMAL); final PdfPCell nbrVc = new PdfPCell(scoreSheet.getDefaultCell()); nbrVc.addElement(nbrV); teamInfo.addCell(nbrVc); // Team division label cell final Paragraph divP = new Paragraph(m_divisionLabel[i], ARIAL_10PT_NORMAL); divP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell divlc = new PdfPCell(scoreSheet.getDefaultCell()); divlc.addElement(divP); divlc.setColspan(2); teamInfo.addCell(divlc); // Team division value cell final Paragraph divV = new Paragraph(m_division[i], COURIER_10PT_NORMAL); final PdfPCell divVc = new PdfPCell(scoreSheet.getDefaultCell()); divVc.setColspan(2); divVc.addElement(divV); teamInfo.addCell(divVc); final PdfPCell temp2 = new PdfPCell(scoreSheet.getDefaultCell()); // temp2.setColspan(2); temp2.addElement(new Paragraph("Team ____", ARIAL_8PT_NORMAL)); teamInfo.addCell(temp2); // Team name label cell final Paragraph nameP = new Paragraph("Team Name:", ARIAL_10PT_NORMAL); nameP.setAlignment(Element.ALIGN_RIGHT); final PdfPCell namelc = new PdfPCell(scoreSheet.getDefaultCell()); namelc.setColspan(2); namelc.addElement(nameP); teamInfo.addCell(namelc); // Team name value cell final Paragraph nameV = new Paragraph(m_name[i], COURIER_10PT_NORMAL); final PdfPCell nameVc = new PdfPCell(scoreSheet.getDefaultCell()); nameVc.setColspan(5); nameVc.addElement(nameV); teamInfo.addCell(nameVc); // add team info cell to the team table final PdfPCell teamInfoCell = new PdfPCell(scoreSheet.getDefaultCell()); teamInfoCell.addElement(teamInfo); teamInfoCell.setColspan(2); scoreSheet.addCell(teamInfoCell); if (null != m_goalsTable) { final PdfPCell goalCell = new PdfPCell(m_goalsTable); goalCell.setBorder(0); goalCell.setPadding(0); goalCell.setColspan(2); scoreSheet.addCell(goalCell); } scoreSheet.addCell(desC); scoreSheet.addCell(sciC); if (null != m_copyright) { final Phrase copyright = new Phrase("\u00A9" + m_copyright, f6i); final PdfPCell copyrightC = new PdfPCell(scoreSheet.getDefaultCell()); copyrightC.addElement(copyright); copyrightC.setBorder(0); copyrightC.setHorizontalAlignment(Element.ALIGN_CENTER); copyrightC.setColspan(2); scoreSheet.addCell(copyrightC); } // the cell in the whole page table that will contain the single score // sheet final PdfPCell scoresheetCell = new PdfPCell(scoreSheet); scoresheetCell.setBorder(0); scoresheetCell.setPadding(0); // Interior borders between scoresheets on a page if (!orientationIsPortrait) { if (i % 2 == 0) { scoresheetCell.setPaddingRight(0.1f * POINTS_PER_INCH); } else { scoresheetCell.setPaddingLeft(0.1f * POINTS_PER_INCH); } } // Add the current scoresheet to the page wholePage.addCell(scoresheetCell); // Add the current table of scoresheets to the document if (orientationIsPortrait || (i % 2 != 0)) { pdfDoc.add(wholePage); } } // Add a blank cells to complete the table of the last page if (!orientationIsPortrait && m_numSheets % 2 != 0) { final PdfPCell blank = new PdfPCell(); blank.setBorder(0); wholePage.addCell(blank); pdfDoc.add(wholePage); } pdfDoc.close(); }
From source file:fll.web.report.FinalComputedScores.java
License:Open Source License
/** * Generate the actual report./* w w w . j a v a 2s.c om*/ */ private void generateReport(final Connection connection, final OutputStream out, final ChallengeDescription challengeDescription, final String challengeTitle, final Tournament tournament, final PdfPageEventHelper pageHandler, final Set<Integer> bestTeams) throws SQLException, IOException { if (tournament.getTournamentID() != Queries.getCurrentTournament(connection)) { throw new FLLRuntimeException( "Cannot generate final score report for a tournament other than the current tournament"); } final WinnerType winnerCriteria = challengeDescription.getWinner(); final TournamentSchedule schedule; if (TournamentSchedule.scheduleExistsInDatabase(connection, tournament.getTournamentID())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Found a schedule for tournament: " + tournament); } schedule = new TournamentSchedule(connection, tournament.getTournamentID()); } else { schedule = null; } try { // This creates our new PDF document and declares it to be in portrait // orientation final Document pdfDoc = PdfUtils.createPortraitPdfDoc(out, pageHandler); final Iterator<String> agIter = Queries.getAwardGroups(connection).iterator(); while (agIter.hasNext()) { final String awardGroup = agIter.next(); final ScoreCategory[] subjectiveCategories = challengeDescription.getSubjectiveCategories() .toArray(new ScoreCategory[0]); // Figure out how many subjective categories have weights > 0. final double[] weights = new double[subjectiveCategories.length]; int nonZeroWeights = 0; for (int catIndex = 0; catIndex < subjectiveCategories.length; catIndex++) { weights[catIndex] = subjectiveCategories[catIndex].getWeight(); if (weights[catIndex] > 0.0) { nonZeroWeights++; } } // Array of relative widths for the columns of the score page // Array length varies with the number of subjective scores weighted > // 0. final int numColumnsLeftOfSubjective = 3; final int numColumnsRightOfSubjective = 2; final float[] relativeWidths = new float[numColumnsLeftOfSubjective + nonZeroWeights + numColumnsRightOfSubjective]; relativeWidths[0] = 3f; relativeWidths[1] = 1.0f; relativeWidths[2] = 1.0f; relativeWidths[relativeWidths.length - numColumnsRightOfSubjective] = 1.5f; relativeWidths[relativeWidths.length - numColumnsRightOfSubjective + 1] = 1.5f; for (int i = numColumnsLeftOfSubjective; i < numColumnsLeftOfSubjective + nonZeroWeights; i++) { relativeWidths[i] = 1.5f; } // Create a table to hold all the scores for this division final PdfPTable divTable = new PdfPTable(relativeWidths); divTable.getDefaultCell().setBorder(0); divTable.setWidthPercentage(100); final PdfPTable header = createHeader(challengeTitle, tournament.getName(), awardGroup); final PdfPCell headerCell = new PdfPCell(header); headerCell.setColspan(relativeWidths.length); divTable.addCell(headerCell); if (LOGGER.isTraceEnabled()) { LOGGER.trace("num relative widths: " + relativeWidths.length); for (int i = 0; i < relativeWidths.length; ++i) { LOGGER.trace("\twidth[" + i + "] = " + relativeWidths[i]); } } writeColumnHeaders(schedule, weights, subjectiveCategories, relativeWidths, challengeDescription, divTable); writeScores(connection, subjectiveCategories, weights, relativeWidths, awardGroup, winnerCriteria, tournament, divTable, bestTeams); // Add the division table to the document pdfDoc.add(divTable); // If there is another division to process, start it on a new page if (agIter.hasNext()) { pdfDoc.newPage(); } } pdfDoc.close(); } catch (final ParseException pe) { throw new RuntimeException("Error parsing category weight!", pe); } catch (final DocumentException de) { throw new RuntimeException("Error creating PDF document!", de); } }
From source file:fr.pigouchet.gestion.util.GeneratePdf.java
public static void createPageByCategory(Categorie category) { loadAllData();//w w w .jav a 2 s . co m Document document = new Document(PageSize.A4, 36, 36, 54, 36); try { PdfWriter.getInstance(document, new FileOutputStream(FILE + "/Fiche " + category.getNom() + ".pdf")); document.open(); PdfPTable table = oneCategory(category); document.add(table); document.newPage(); document.close(); if (Desktop.isDesktopSupported()) { try { File myFile = new File(FILE + "/Fiche " + category.getNom() + ".pdf"); Desktop.getDesktop().open(myFile); } catch (IOException ex) { // no application registered for PDFs } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:fr.pigouchet.gestion.util.GeneratePdf.java
public static void createFullPage() throws IOException { loadAllData();//from ww w .ja va2 s .c o m Document document = new Document(PageSize.A4, 36, 36, 54, 36); try { writer = PdfWriter.getInstance(document, new FileOutputStream(FILE + "/Tous les produits.pdf")); document.open(); for (Categorie categorie : dataCate) { PdfPTable table = allSubCategory(categorie, document); document.add(table); document.newPage(); passed = false; } //System.out.println(writer.getPageNumber()); document.close(); if (Desktop.isDesktopSupported()) { try { File myFile = new File(FILE + "/Tous les produits.pdf"); Desktop.getDesktop().open(myFile); } catch (IOException ex) { // no application registered for PDFs } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:fxml.test.PDFService.java
public void generatePdf() { // Document document = new Document(PageSize.A4.rotate()); Document document = new Document(new Rectangle(1008, 612)); try {//from w ww . j a v a 2s. c o m PdfWriter.getInstance(document, new FileOutputStream("table.pdf")); document.setMargins(90, 80, 35, 40); document.open(); if (!list.isEmpty()) { list.add("Total Credit"); list.add("Total GPA"); list.add("Letter Grade"); list.add("Cumulative"); list.add("Remarks"); list.add("GC"); if (inputs.get(1).contains("8th")) { list.add("PC. No"); list.add("OC. No"); list.add("D/AF. No"); list.add("Others"); } int totalCoureseSize = list.size(); int totalCourseLoop = totalCoureseSize / 12; int courseLoopVariable = 0; if (totalCoureseSize % 12 > 0) { totalCourseLoop += 1; } int totalStudentSize = studentList.size(); int totalStudentLoop = (totalStudentSize / 15); int studentLoopVariable = 0; if (totalStudentSize % 15 > 0) { totalStudentLoop += 1; } if (totalStudentLoop > 0) { for (studentLoopVariable = 0; studentLoopVariable < totalStudentLoop; studentLoopVariable++) { //start print the courses when it is multiple of 12 if (totalCourseLoop > 0) { for (courseLoopVariable = 0; courseLoopVariable < totalCourseLoop; courseLoopVariable++) { int courseStart = courseLoopVariable * 12; int studentStart = studentLoopVariable * 15; //start document header document.add(createDocumentHeader()); //end document header //start table header PdfPTable table = createTableHeader(courseStart); //end table header //start table body table = createTableBody(studentStart, courseStart, table); //end table body //adding table and footer table.setSpacingAfter(27); document.add(table); document.add(createFooter1()); document.add(createFooter2()); //end adding table and footer //go to new page.. document.newPage(); } } } } } document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { AlertMessage.showAlertMessage(Alert.AlertType.ERROR, "Error creating Pdf document.Please try again"); e.printStackTrace(); } }
From source file:generadorPDF.generarPDF.java
private static void addTitlePage(Document document, Resolucion res) throws DocumentException { Paragraph preface = new Paragraph(); // We add one empty line addEmptyLine(preface, 1);/* w w w . j a va2 s.c o m*/ // Lets write a big header preface.add(new Paragraph("Consejo Profesional de Informatica de Santiago del Estero", catFont)); addEmptyLine(preface, 1); // Will create: Report generated by: _name, _date preface.add(new Paragraph("Comision Directiva del Consejo, " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ smallBold)); addEmptyLine(preface, 2); preface.add(new Paragraph("Resolucion N" + res.getNumero_resolucion() + "", smallBold)); addEmptyLine(preface, 3); preface.add(new Paragraph("Esta Resolucion de tipo " + res.getTipo() + " formulada para notificar al socio con legajo: " + res.getLegajo_socio() + " de su actual estado como socio del Consejo.\n" + res.getDescripcion_solicitud() + " " + res.getDescripcion_resolucion() + " en la fecha " + res.getFecha(), cuerpo)); document.add(preface); // Start a new page document.newPage(); }