List of usage examples for com.itextpdf.text Document setMargins
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom)
From source file:org.smap.sdal.managers.MiscPDFManager.java
License:Open Source License
public void createUsagePdf(Connection sd, OutputStream outputStream, String basePath, HttpServletResponse response, int o_id, int month, int year, String period, String org_name) { PreparedStatement pstmt = null; if (org_name == null) { org_name = "None"; }/*from w w w . j av a2 s. c o m*/ try { String filename; // 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); filename = org_name + "_" + year + "_" + month + ".pdf"; /* * Get the usage results */ String sql = "SELECT users.id as id," + "users.ident as ident, " + "users.name as name, " + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id " + "and se.status = 'success' " + "and se.subscriber = 'results_db' " + "and extract(month from upload_time) = ? " // current month + "and extract(year from upload_time) = ? " // current year + "and ue.user_name = users.ident) as month, " + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id " + "and se.status = 'success' " + "and se.subscriber = 'results_db' " + "and ue.user_name = users.ident) as all_time " + "from users " + "where users.o_id = ? " + "and not users.temporary " + "order by users.ident;"; pstmt = sd.prepareStatement(sql); pstmt.setInt(1, month); pstmt.setInt(2, year); pstmt.setInt(3, o_id); log.info("Get Usage Data: " + pstmt.toString()); // 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); 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 */ String stationaryName = basePath + File.separator + "misc" + File.separator + "UsageReportTemplate.pdf"; File stationaryFile = new File(stationaryName); ByteArrayOutputStream baos = null; ByteArrayOutputStream baos_s = null; PdfWriter writer = null; /* * Create document in two passes, the second pass adds the letter head */ // Create the underlying document as a byte array Document document = new Document(PageSize.A4); document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); if (stationaryFile.exists()) { baos = new ByteArrayOutputStream(); baos_s = new ByteArrayOutputStream(); writer = PdfWriter.getInstance(document, baos); } else { writer = PdfWriter.getInstance(document, outputStream); } writer.setInitialLeading(12); writer.setPageEvent(new PageSizer()); document.open(); // Write the usage data ResultSet resultSet = pstmt.executeQuery(); PdfPTable table = new PdfPTable(4); // Add the header row table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY); table.getDefaultCell().setBackgroundColor(VLG); table.addCell("User Id"); table.addCell("User Name"); table.addCell("Usage in Period"); table.addCell("All Time Usage"); table.setHeaderRows(1); // Add the user data int total = 0; int totalAllTime = 0; table.getDefaultCell().setBackgroundColor(null); while (resultSet.next()) { String ident = resultSet.getString("ident"); String name = resultSet.getString("name"); String monthUsage = resultSet.getString("month"); int monthUsageInt = resultSet.getInt("month"); String allTime = resultSet.getString("all_time"); int allTimeInt = resultSet.getInt("all_time"); table.addCell(ident); table.addCell(name); table.addCell(monthUsage); table.addCell(allTime); total += monthUsageInt; totalAllTime += allTimeInt; } // Add the totals table.getDefaultCell().setBackgroundColor(VLG); table.addCell("Totals: "); table.addCell(" "); table.addCell(String.valueOf(total)); table.addCell(String.valueOf(totalAllTime)); document.add(table); document.close(); if (stationaryFile.exists()) { // Step 2 - Populate the fields in the stationary PdfReader s_reader = new PdfReader(stationaryName); PdfStamper s_stamper = new PdfStamper(s_reader, baos_s); AcroFields pdfForm = s_stamper.getAcroFields(); Set<String> fields = pdfForm.getFields().keySet(); for (String key : fields) { log.info("Field: " + key); } pdfForm.setField("billing_period", period); pdfForm.setField("organisation", org_name); s_stamper.setFormFlattening(true); s_stamper.close(); // Step 3 - Apply the stationary to the underlying document PdfReader reader = new PdfReader(baos.toByteArray()); // Underlying document PdfReader f_reader = new PdfReader(baos_s.toByteArray()); // Filled in stationary PdfStamper stamper = new PdfStamper(reader, outputStream); PdfImportedPage letter1 = stamper.getImportedPage(f_reader, 1); int n = reader.getNumberOfPages(); PdfContentByte background; for (int i = 0; i < n; i++) { background = stamper.getUnderContent(i + 1); if (i == 0) { background.addTemplate(letter1, 0, 0); } } stamper.close(); reader.close(); } } catch (SQLException e) { log.log(Level.SEVERE, "SQL Error", e); } catch (Exception e) { log.log(Level.SEVERE, "Exception", e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } }
From source file:org.smap.sdal.managers.MiscPDFManager.java
License:Open Source License
public void createTasksPdf(Connection sd, OutputStream outputStream, String basePath, HttpServletRequest request, HttpServletResponse response, int tgId) { try {//from ww w . ja v a2 s .c om // 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"); } 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); /* * Get the tasks for this task group */ String urlprefix = request.getScheme() + "://" + request.getServerName(); TaskManager tm = new TaskManager(localisation, tz); TaskListGeoJson t = tm.getTasks(sd, urlprefix, 0, tgId, 0, false, 0, null, "all", 0, 0, "scheduled", "desc"); PdfWriter writer = null; String filename = "tasks.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); setFilenameInResponse(filename, response); } Document document = new Document(PageSize.A4); document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); writer = PdfWriter.getInstance(document, outputStream); writer.setInitialLeading(12); writer.setPageEvent(new PageSizer()); document.open(); PdfPTable table = new PdfPTable(4); // Add the header row table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY); table.getDefaultCell().setBackgroundColor(VLG); table.addCell("Form Name"); table.addCell("Task Name"); table.addCell("Status"); table.addCell("Assigned To"); table.setHeaderRows(1); // Add the task data table.getDefaultCell().setBackgroundColor(null); for (TaskFeature tf : t.features) { TaskProperties p = tf.properties; table.addCell(p.survey_name); table.addCell(p.name); table.addCell(p.status); table.addCell(p.assignee_name); } document.add(table); 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.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 {// www. j a v a 2s .c o 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;/* ww w . j a v a2s .co 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.techytax.report.helper.PdfReportHelper.java
License:Open Source License
public byte[] createVatReportBytes(VatReportData vatReportData) { Document document = new Document(); document.setMargins(0, 0, 40, 40); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); try {/* ww w .java2s . co m*/ PdfWriter.getInstance(document, byteOutputStream); document.open(); PdfPTable subTable = new PdfPTable(1); PdfPCell cell = new PdfPCell(new Paragraph("")); subTable.addCell(cell); PdfPTable table = new PdfPTable(1); addSpace(table); Paragraph chunk = new Paragraph("btw declaratie aangever gegevens", headerFont); cell = new PdfPCell(chunk); cell.setBorder(PdfPCell.NO_BORDER); table.addCell(cell); subTable = new PdfPTable(2); addVatDeclarationData(subTable, vatReportData.getVatDeclarationData()); cell = new PdfPCell(subTable); cell.setBorder(PdfPCell.NO_BORDER); table.addCell(cell); addSpace(table); addVatData(table, vatReportData.getVatDeclarationData()); addSpace(table); addTotalsIn(vatReportData, table); addSpace(table); addTotalsOut(vatReportData, table); addSpace(table); addSpace(table); addJournalsIn(vatReportData, table); addJournalsOut(vatReportData, table); document.add(table); LineSeparator horizontalLine = new LineSeparator(); BaseColor lineColor = new BaseColor(141, 141, 141); horizontalLine.setLineWidth(1f); horizontalLine.setLineColor(lineColor); document.add(horizontalLine); } catch (Exception de) { de.printStackTrace(); } document.close(); return byteOutputStream.toByteArray(); }
From source file:org.tvd.thptty.management.report.Report.java
public void createFile(int kind) { Document document = new Document(); document.setPageSize(PageSize.A4);/* www .j av a2s . c o m*/ if (kind == 1) { document.setMargins(37, 37, 37, 37); } else if (kind == 2) { } 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:pdf.CoverLetterUtility.java
License:Apache License
public void createPdf() { System.out.println("Creating cover letter..."); Document document = new Document(); document.setPageSize(PageSize.A4);// w w w .j a v a 2s.c o m document.setMargins(62, 48, 36, 36); baos = new ByteArrayOutputStream(); try { 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); Collections.sort(pagamento.getBeneficios(), new Comparator()); document.open();/* ww w . jav a2s.com*/ document.add(createTable(pagamento, dados)); document.close(); }
From source file:pdf.PdfUtility.java
public void createPdf() { Logger.getLogger(PdfUtility.class.getName()).log(Level.INFO, "Creating pdf..."); Document document = new Document(); try {//from w w w . j a v a 2s. c o m document.setPageSize(PageSize.A4); document.setMargins(62, 48, 36, 36); baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); addTitle(document); addData(document); } catch (DocumentException ex) { Logger.getLogger(PdfUtility.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(PdfUtility.class.getName()).log(Level.SEVERE, null, ex); } finally { document.close(); } }
From source file:pdfcompressor.PDFCompressor.java
public void outputPDF(String pathToOutput) throws FileNotFoundException, DocumentException, BadElementException, IOException { com.itextpdf.text.Image itextImg; Document outDocument = new Document(); outDocument.setMargins(0f, 0f, 0f, 0f); PdfWriter writer = PdfWriter.getInstance(outDocument, new FileOutputStream(pathToOutput)); writer.setFullCompression();//from www.j a va 2s. c o m writer.open(); outDocument.open(); int progress = 0; for (java.awt.Image img : getBuffedImg()) { itextImg = Image.getInstance(getImageByteArray(img, compressRate)); itextImg.scaleToFit(595f, 842f); outDocument.add(itextImg); for (ProgressListener listener : saveListener) { listener.haveProgress(++progress, numOfPages); } } outDocument.close(); writer.close(); for (ProgressListener listener : saveListener) { listener.finished(); } }