List of usage examples for com.itextpdf.text PageSize A4
Rectangle A4
To view the source code for com.itextpdf.text PageSize A4.
Click Source Link
From source file:org.smap.sdal.managers.PDFSurveyManager.java
License:Open Source License
public String createPdf(OutputStream outputStream, String basePath, String serverRoot, String remoteUser, String language, boolean generateBlank, String filename, boolean landscape, // Set true if landscape HttpServletResponse response) throws Exception { if (language != null) { language = language.replace("'", "''"); // Escape apostrophes } else {//from w w w. ja v a 2s. co m language = "none"; } mExcludeEmpty = survey.exclude_empty; User user = null; ServerManager serverManager = new ServerManager(); ServerData serverData = serverManager.getServer(sd, localisation); UserManager um = new UserManager(localisation); int[] repIndexes = new int[20]; // Assume repeats don't go deeper than 20 levels Document document = null; PdfWriter writer = null; PdfReader reader = null; PdfStamper stamper = null; try { // Get fonts and embed them String os = System.getProperty("os.name"); log.info("Operating System:" + os); if (os.startsWith("Mac")) { FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols"); //FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default"); FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans"); FontFactory.register("/Library/Fonts/NotoSans-Bold.ttf", "notosansbold"); FontFactory.register("/Library/Fonts/NotoSansBengali-Regular.ttf", "bengali"); FontFactory.register("/Library/Fonts/NotoSansBengali-Bold.ttf", "bengalibold"); } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) { // Linux / Unix FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols"); FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Bold.ttf", "notosansbold"); FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Regular.ttf", "bengali"); FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Bold.ttf", "bengalibold"); } Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFontLink = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFont = FontFactory.getFont("notosans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); defaultFontBold = FontFactory.getFont("notosansbold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); arabicFont = FontFactory.getFont("arabic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); bengaliFont = FontFactory.getFont("bengali", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); bengaliFontBold = FontFactory.getFont("bengalibold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); defaultFontLink.setColor(BaseColor.BLUE); /* * Get the results and details of the user that submitted the survey */ log.info("User Ident who submitted the survey: " + survey.instance.user); String userName = survey.instance.user; if (userName == null) { userName = remoteUser; } if (userName != null) { user = um.getByIdent(sd, userName); } // If a filename was not specified then get one from the survey data // This filename is returned to the calling program so that it can be used as a permanent name for the temporary file created here // If the PDF is to be returned in an http response then the header is set now before writing to the output stream log.info("Filename passed to createPDF is: " + filename); if (filename == null) { filename = survey.getInstanceName() + ".pdf"; } else { if (!filename.endsWith(".pdf")) { filename += ".pdf"; } } // If the PDF is to be returned in an http response then set the file name now if (response != null) { log.info("Setting filename to: " + filename); GeneralUtilityMethods.setFilenameInResponse(filename, response); } /* * Get a template for the PDF report if it exists * The template name will be the same as the XLS form name but with an extension of pdf */ File templateFile = GeneralUtilityMethods.getPdfTemplate(basePath, survey.displayName, survey.p_id); /* * Get dependencies between Display Items, for example if a question result should be added to another * question's results */ GlobalVariables gv = new GlobalVariables(); if (!generateBlank) { for (int i = 0; i < survey.instance.results.size(); i++) { getDependencies(gv, survey.instance.results.get(i), survey, i); } } gv.mapbox_key = serverData.mapbox_default; int oId = GeneralUtilityMethods.getOrganisationId(sd, remoteUser); languageIdx = GeneralUtilityMethods.getLanguageIdx(survey, language); if (templateFile.exists()) { log.info("PDF Template Exists"); String templateName = templateFile.getAbsolutePath(); reader = new PdfReader(templateName); stamper = new PdfStamper(reader, outputStream); for (int i = 0; i < survey.instance.results.size(); i++) { fillTemplate(gv, stamper.getAcroFields(), survey.instance.results.get(i), basePath, null, i, serverRoot, stamper, oId); } if (user != null) { fillTemplateUserDetails(stamper.getAcroFields(), user, basePath); } stamper.setFormFlattening(true); } else { log.info("++++No template exists creating a pdf file programmatically"); /* * Create a PDF without the stationary * If we need to add a letter head then create document in two passes, the second pass adds the letter head * Else just create the document directly in a single pass */ Parser parser = getXMLParser(); // Step 1 - Create the underlying document as a byte array if (landscape) { document = new Document(PageSize.A4.rotate()); } else { document = new Document(PageSize.A4); } document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); writer = PdfWriter.getInstance(document, outputStream); writer.setInitialLeading(12); writer.setPageEvent(new PdfPageSizer(survey.displayName, survey.projectName, user, basePath, null, marginLeft, marginRight, marginTop_2, marginBottom_2)); document.open(); // If this form has data maintain a list of parent records to lookup ${values} ArrayList<ArrayList<Result>> parentRecords = null; if (!generateBlank) { parentRecords = new ArrayList<ArrayList<Result>>(); } for (int i = 0; i < survey.instance.results.size(); i++) { processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot, generateBlank, 0, i, repIndexes, gv, false, parentRecords, remoteUser, oId); } fillNonTemplateUserDetails(document, user, basePath); // Add appendix if (gv.hasAppendix) { document.newPage(); document.add(new Paragraph("Appendix", defaultFontBold)); for (int i = 0; i < survey.instance.results.size(); i++) { processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot, generateBlank, 0, i, repIndexes, gv, true, parentRecords, remoteUser, oId); } } } } finally { if (document != null) try { document.close(); } catch (Exception e) { } ; if (writer != null) try { writer.close(); } catch (Exception e) { } ; if (stamper != null) try { stamper.close(); } catch (Exception e) { } ; if (reader != null) try { reader.close(); } catch (Exception e) { } ; } return filename; }
From source file:org.smap.sdal.managers.PDFTableManager.java
License:Open Source License
public void createPdf(Connection sd, OutputStream outputStream, ArrayList<ArrayList<KeyValue>> dArray, SurveyViewDefn mfc, ResourceBundle localisation, String tz, boolean landscape, String remoteUser, String basePath, String title, String project) { User user = null;/* w w w.j a v a 2 s . c o m*/ UserManager um = new UserManager(localisation); try { user = um.getByIdent(sd, remoteUser); // Get fonts and embed them String os = System.getProperty("os.name"); log.info("Operating System:" + os); if (os.startsWith("Mac")) { FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols"); FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default"); FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans"); } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) { // Linux / Unix FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols"); FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default"); FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans"); } Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); ArrayList<PdfColumn> cols = getPdfColumnList(mfc, dArray, localisation); ArrayList<String> tableHeader = new ArrayList<String>(); for (PdfColumn col : cols) { tableHeader.add(col.displayName); } /* * Create a PDF without the stationary */ PdfWriter writer = null; /* * If we need to add a letter head then create document in two passes, the second pass adds the letter head * Else just create the document directly in a single pass */ Parser parser = getXMLParser(); // Step 1 - Create the underlying document as a byte array Document document = null; if (landscape) { document = new Document(PageSize.A4.rotate()); } else { document = new Document(PageSize.A4); } document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); writer = PdfWriter.getInstance(document, outputStream); writer.setInitialLeading(12); writer.setPageEvent(new PdfPageSizer(title, project, user, basePath, tableHeader, marginLeft, marginRight, marginTop_2, marginBottom_2)); document.open(); document.add(new Chunk("")); // Ensure there is something in the page so at least a blank document will be created processResults(parser, document, dArray, cols, basePath); document.close(); } catch (SQLException e) { log.log(Level.SEVERE, "SQL Error", e); } catch (Exception e) { log.log(Level.SEVERE, "Exception", e); } }
From source file:org.tvd.thptty.management.report.Report.java
public void createFile(int kind) { Document document = new Document(); document.setPageSize(PageSize.A4); if (kind == 1) { document.setMargins(37, 37, 37, 37); } else if (kind == 2) { }//from w w w . ja va 2 s . c o m try { File file = new File(getFullPathFile()); PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); addMetaData(document); //addTitlePage(document); addContent(document, kind); } catch (Exception e) { e.printStackTrace(); } finally { document.close(); } }
From source file:org.tvd.thptty.management.report.Report.java
private PdfPTable createSubjectPointTable() throws BadElementException { int countCell = cellTitles.length; PdfPTable table = new PdfPTable(countCell); table.setWidthPercentage(100);//from w w w .j a va2s . c o m for (int i = 0; i < countCell; i++) { Phrase phrase = new Phrase(cellTitles[i], tahomaFont); PdfPCell cx = new PdfPCell(phrase); cx.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cx); } table.setHeaderRows(1); Phrase phrase = null; java.util.List<TYStudent> students = ActionUtil.getStudentsInClass(courses, tyClass.getClassId()); for (int i = 0; i < students.size(); i++) { //index phrase = new Phrase(String.valueOf(i + 1), tahomaFont); table.addCell(phrase); //student full name TYStudent student = students.get(i); student.setFullName(student.getStudentFirstName() + " " + student.getStudentLastName()); phrase = new Phrase(student.getFullName(), tahomaFont); table.addCell(phrase); //speak point float points[] = TYServiceUtil.getPointStudentByPTPF(courses, semester, student.getStudentId(), tySubject.getSubjectId(), WebKeys.SPEAK_POINT, 1); String pointString = TYServiceUtil.floatsToPointString(points); phrase = new Phrase(pointString, smallBold); table.addCell(phrase); //15' point points = TYServiceUtil.getPointStudentByPTPF(courses, semester, student.getStudentId(), tySubject.getSubjectId(), WebKeys.WRITE_POINT, 1); pointString = TYServiceUtil.floatsToPointString(points); phrase = new Phrase(pointString, smallBold); table.addCell(phrase); //45' point points = TYServiceUtil.getPointStudentByPTPF(courses, semester, student.getStudentId(), tySubject.getSubjectId(), WebKeys.WRITE_POINT, 2); pointString = TYServiceUtil.floatsToPointString(points); phrase = new Phrase(pointString, smallBold); table.addCell(phrase); //90' point points = TYServiceUtil.getPointStudentByPTPF(courses, semester, student.getStudentId(), tySubject.getSubjectId(), WebKeys.WRITE_POINT, 3); pointString = TYServiceUtil.floatsToPointString(points); phrase = new Phrase(pointString, smallBold); table.addCell(phrase); //avg point TYStudentPoint studentPointSubject = TYServiceUtil.getStudentAVGPointBySubject(courses, semester, student.getStudentId(), tySubject.getSubjectId()); float avgPointSubject = 0; if (studentPointSubject != null) avgPointSubject = TYServiceUtil.getCutFloat(studentPointSubject.getPoint(), 1); pointString = "" + avgPointSubject; phrase = new Phrase(pointString, smallBold); table.addCell(phrase); } float totalWidth = PageSize.A4.getWidth(); float columnWidths[] = { (float) (0.05 * totalWidth), (float) (0.35 * totalWidth), (float) (0.1 * totalWidth), (float) (0.2 * totalWidth), (float) (0.1 * totalWidth), (float) (0.1 * totalWidth), (float) (0.1 * totalWidth) }; try { table.setWidthPercentage(columnWidths, PageSize.A4); } catch (DocumentException e) { e.printStackTrace(); } return table; }
From source file:org.tvd.thptty.management.report.Report.java
private PdfPTable createStatisticsStudentPointTable() throws BadElementException { PdfPTable table = new PdfPTable(15); table.setWidthPercentage(100);/*from w w w . j av a 2 s. co m*/ for (int i = 0; i < 3; i++) { Phrase phrase = new Phrase(cellTitles[i], tahomaBoldFont); PdfPCell cx = new PdfPCell(phrase); cx.setHorizontalAlignment(Element.ALIGN_CENTER); cx.setVerticalAlignment(Element.ALIGN_MIDDLE); cx.setRowspan(3); table.addCell(cx); } for (int i = 3; i < 5; i++) { Phrase phrase = new Phrase(cellTitles[i], tahomaBoldFont); PdfPCell cx = new PdfPCell(phrase); cx.setHorizontalAlignment(Element.ALIGN_CENTER); cx.setVerticalAlignment(Element.ALIGN_MIDDLE); cx.setColspan(6); table.addCell(cx); } for (int i = 5; i < 11; i++) { Phrase phrase = new Phrase(cellTitles[i], tahomaBoldFont); PdfPCell cx = new PdfPCell(phrase); cx.setHorizontalAlignment(Element.ALIGN_CENTER); cx.setVerticalAlignment(Element.ALIGN_MIDDLE); cx.setColspan(2); table.addCell(cx); } for (int i = 11; i < 23; i++) { Phrase phrase = new Phrase(cellTitles[i], tahomaBoldFont); PdfPCell cx = new PdfPCell(phrase); cx.setHorizontalAlignment(Element.ALIGN_CENTER); cx.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cx); } table.setHeaderRows(3); Phrase phrase = null; for (int i = 0; rows != null && i < rows.size(); i++) { for (int k = 0; k < rows.get(i).getListCells().size(); k++) { phrase = new Phrase(rows.get(i).getListCells().get(k).getCellName(), tahomaSmallFont); PdfPCell cx = new PdfPCell(phrase); cx.setHorizontalAlignment(Element.ALIGN_CENTER); cx.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cx); } } float totalWidth = PageSize.A4.getWidth(); float columnWidths[] = new float[15]; for (int i = 0; i < columnWidths.length; i++) { columnWidths[i] = (float) (1.0 / 15) * totalWidth; } try { table.setWidthPercentage(columnWidths, PageSize.A4); } catch (DocumentException e) { e.printStackTrace(); } return table; }
From source file:org.unesco.jisis.printsort.BarCodeGenerator.java
public void generateBarCode() { /** Step 1: Create a Document*/ Document document = new Document(PageSize.A4, 50, 50, 50, 50); try {//from ww w. ja va 2s .com /** Step 2: Create PDF Writer*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("sanjaalDotCom_BarCode1.pdf")); /** Step 3: Open the document so that we can write over it.*/ document.open(); /** Step 4: We have to create a set of contents.*/ contentByte = writer.getDirectContent(); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); table.getDefaultCell().setFixedHeight(70); String myText = "www.sanjaal.com"; // Text to encode table.addCell("CODE 39"); table.addCell(new Phrase(new Chunk(createBarCode39(myText.toUpperCase()), 0, 0))); table.addCell("CODE 39 EXTENDED"); table.addCell(new Phrase(new Chunk(createBarcode39Extended(myText), 0, 0))); table.addCell("CODE 128"); table.addCell(new Phrase(new Chunk(createBarcode128(myText), 0, 0))); table.addCell("CODE INTERLEAVED"); String myTextNum = "12345"; table.addCell(new Phrase(new Chunk(createBarcodeInter25(myTextNum), 0, 0))); table.addCell("CODE POSTNET"); table.addCell(new Phrase(new Chunk(createBarcodePostnet(myTextNum), 0, 0))); table.addCell("CODE PLANET"); table.addCell(new Phrase(new Chunk(createBarcodePostnetPlanet(myTextNum), 0, 0))); String myTextEAN13 = "1234567890123"; table.addCell("CODE EAN"); table.addCell(new Phrase(new Chunk(createBarcodeEAN(myTextEAN13), 0, 0))); table.addCell("CODE EAN\nWITH\nSUPPLEMENTAL 5"); table.addCell(new Phrase(new Chunk(createBARCodeEANSUPP(myTextEAN13, "12345"), 0, 0))); document.add(table); } catch (Exception de) { de.printStackTrace(); } // step 5: we close the document document.close(); }
From source file:org.zaproxy.zap.extension.alertReport.AlertReportExportPDF.java
License:Apache License
public boolean exportAlert(java.util.List<java.util.List<Alert>> alerts, String fileName, ExtensionAlertReportExport extensionExport) { Document document = new Document(PageSize.A4); try {//ww w . j ava2 s . c o m // Document documentAdd = null; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); boolean attach = false; // add attach document is exist if (!extensionExport.getParams().getDocumentAttach().isEmpty()) { PdfReader reader = new PdfReader(extensionExport.getParams().getDocumentAttach()); int n = reader.getNumberOfPages(); PdfImportedPage page; // Go through all pages for (int i = 1; i <= n; i++) { page = writer.getImportedPage(reader, i); Image instance = Image.getInstance(page); instance.scalePercent(95f); document.add(instance); } attach = true; } if (!attach) { addMetaData(document, extensionExport); addTitlePage(document, extensionExport); } for (int i = 0; i < alerts.size(); i++) { java.util.List<Alert> alertAux = alerts.get(i); addContent(document, alertAux, extensionExport); } document.close(); return true; } catch (Exception e) { logger.error(e.getMessage(), e); document.close(); return false; } }
From source file:Outras.GerarPdf.java
public GerarPdf(Os os) { //Criar um documento vazio Document documentoPDF = new Document(); try {/*from w w w . j a v a2 s. c om*/ //cria uma instancia do documento e da o nome dele na saida informada PdfWriter.getInstance(documentoPDF, new FileOutputStream("C:\\OrdensDeServico\\OS_" + os.getId())); //abertura do documento documentoPDF.open(); //especificar o layout da pagina; j cria a primeria pagina documentoPDF.setPageSize(PageSize.A4); ////adicionando pargrafos na primeira folha //adicionando titulo documentoPDF.addTitle("Ordem de Servio"); //adicionando imagens da OS e redimensionando Image imagem = Image.getInstance( "C:\\Users\\aluno\\Documents\\NetBeansProjects\\e-commerce\\src\\material\\imagemOs.png"); imagem.scaleToFit(200, 200); documentoPDF.add(imagem); //adicionando o primeiro paragrafo documentoPDF.add(new Paragraph("ORDEM DE SERVIO EMITIDA PELO CARRINHO DO USUARIO: " + os.getEntrega().getEndereco().getUsuario().getNome())); documentoPDF .add(new Paragraph("Endereo de entrega: " + os.getEntrega().getEndereco().getLogradouro())); documentoPDF.add(new Paragraph("Entregador: " + os.getEntrega().getFuncionario().getNome())); documentoPDF.add(new Paragraph("Produtos: ")); for (Produto p : os.getCarrinho().getProdutos()) { documentoPDF.add(new LineSeparator()); documentoPDF.add(new Paragraph(p.getNome())); } documentoPDF.add(new LineSeparator()); } catch (DocumentException de) { JOptionPane.showMessageDialog(null, "Erro ao gerar o pdf" + de.getMessage()); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Erro ao gerar o pdf" + ioe.getMessage()); } finally { documentoPDF.close(); } }
From source file:pdf.CoverLetterUtility.java
License:Apache License
public void createPdf() { System.out.println("Creating cover letter..."); Document document = new Document(); document.setPageSize(PageSize.A4); document.setMargins(62, 48, 36, 36); baos = new ByteArrayOutputStream(); try {// w w w. j a v a2s. c om PdfWriter.getInstance(document, baos); } catch (DocumentException ex) { Logger.getLogger(CoverLetterUtility.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } document.open(); document.addAuthor("vitaelifetime@gmail.com"); document.addCreationDate(); addTitle(document); addReference(document); addSalutation(document); addIntroduction(document); addWhyMe(document); addWhyYou(document); addConclusion(document); document.close(); }
From source file:pdf.GeradorPDF.java
public void createPdf(String filename, Pagamento pagamento, DadosEspecificos dados) throws IOException, DocumentException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.setPageSize(PageSize.A4.rotate()); document.setMargins(0, 0, 50, 50);//from ww w . j a v a2 s . c o m Collections.sort(pagamento.getBeneficios(), new Comparator()); document.open(); document.add(createTable(pagamento, dados)); document.close(); }