List of usage examples for com.itextpdf.text Document open
boolean open
To view the source code for com.itextpdf.text Document open.
Click Source Link
From source file:at.laborg.briss.utils.DocumentCropper.java
License:Open Source License
private static File copyToMultiplePages(final CropDefinition cropDefinition, final PdfMetaInformation pdfMetaInformation) throws IOException, DocumentException { PdfReader reader = new PdfReader(cropDefinition.getSourceFile().getAbsolutePath()); HashMap<String, String> map = SimpleNamedDestination.getNamedDestination(reader, false); Document document = new Document(); File resultFile = File.createTempFile("cropped", ".pdf"); PdfSmartCopy pdfCopy = new PdfSmartCopy(document, new FileOutputStream(resultFile)); document.open(); Map<Integer, List<String>> pageNrToDestinations = new HashMap<Integer, List<String>>(); for (String single : map.keySet()) { StringTokenizer st = new StringTokenizer(map.get(single), " "); if (st.hasMoreElements()) { String pageNrString = (String) st.nextElement(); int pageNr = Integer.parseInt(pageNrString); List<String> singleList = (pageNrToDestinations.get(pageNr)); if (singleList == null) { singleList = new ArrayList<String>(); singleList.add(single);/*from w w w.j a va 2 s . c om*/ pageNrToDestinations.put(pageNr, singleList); } else { singleList.add(single); } } } int outputPageNumber = 0; for (int pageNumber = 1; pageNumber <= pdfMetaInformation.getSourcePageCount(); pageNumber++) { PdfImportedPage pdfPage = pdfCopy.getImportedPage(reader, pageNumber); pdfCopy.addPage(pdfPage); outputPageNumber++; List<String> destinations = pageNrToDestinations.get(pageNumber); if (destinations != null) { for (String destination : destinations) pdfCopy.addNamedDestination(destination, outputPageNumber, new PdfDestination(PdfDestination.FIT)); } List<Float[]> rectangles = cropDefinition.getRectanglesForPage(pageNumber); for (int j = 1; j < rectangles.size(); j++) { pdfCopy.addPage(pdfPage); outputPageNumber++; } } document.close(); pdfCopy.close(); reader.close(); return resultFile; }
From source file:automatedbillingsoftware.helper.HtmlToPdf.java
public void createPdf(String file, HashMap<String, Object> scopes) throws IOException, DocumentException { // step 1// w w w .ja v a2 s . com Document document = new Document(PageSize.A4); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setTagged(); // step 3 document.open(); // step 4 // String readHtml = readHtml(HTML); System.out.println("challan" + DEST.contains("Challan-")); String readHtml = DEST.contains("Challan-") ? getDefaultTempProperties().getProperty("challan") : getDefaultTempProperties().getProperty("invoice"); System.out.println("readHtml=>" + readHtml); String testTemplate = getTestTemplate(readHtml, scopes); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new StringReader(testTemplate)); // XMLWorkerHelper.getInstance().parseXHtml(writer, ); // step 5 document.close(); }
From source file:automatedbillingsoftware.helper.HtmlToPdf1.java
/** * Creates a PDF with the words "Hello World" * * @param file//from w w w. ja va 2 s . co m * @throws IOException * @throws DocumentException */ public void createPdf(String file, HashMap<String, Object> scopes) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setTagged(); // step 3 document.open(); // step 4 String readHtml = readHtml(HTML); String testTemplate = getTestTemplate(readHtml, scopes); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new StringReader(testTemplate)); // XMLWorkerHelper.getInstance().parseXHtml(writer, ); // step 5 document.close(); }
From source file:bd.gov.forms.web.FormBuilder.java
License:Open Source License
@RequestMapping(value = "/individualpdf", method = RequestMethod.GET) public String individualpdf(@RequestParam(value = "formId", required = true) String formId, @RequestParam(value = "entryId", required = true) String entryId, ModelMap model, HttpServletResponse response) throws IOException { byte[] fileContent = formDao.getTemplateContent(formId); Form form = formDao.getFormWithFields(formId); form.setEntryId(entryId);//from www. j a v a 2 s . co m form = formDao.getEntry(form); String report = ""; Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (fileContent != null) { report = new String(fileContent, "UTF8"); for (Field field : form.getFields()) { if (fieldTypeIsNotOfFileOrNoteOrSection(field)) { report = report.replaceAll("#" + field.getColName() + ":label#", field.getLabel()); report = report.replaceAll("#" + field.getColName() + ":value#", field.getStrVal()); } } } else { // step 2 try { response.reset(); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "inline; filename=test.pdf"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "No-cache"); PdfWriter writer = PdfWriter.getInstance(document, baos); // step 3 document.open(); PdfPCell space; space = new PdfPCell(); space.setBorder(Rectangle.NO_BORDER); space.setColspan(2); space.setFixedHeight(8); PdfPTable table = new PdfPTable(2); PdfPCell cell; report += "<table cellspacing='0' cellpadding='0' style='border:1px solid #aaa;width:98%;'>"; for (Field field : form.getFields()) { if (fieldTypeIsNotOfFileOrNoteOrSection(field)) { report += field.getLabel(); report += field.getStrVal(); table.setWidths(new int[] { 1, 2 }); table.addCell(field.getLabel()); //cell = new PdfPCell(); //cell.setCellEvent(new TextFields(1)); table.addCell(field.getStrVal()); } } document.add(table); document.close(); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception ex) { System.out.println("Could not print reasone::" + ex.toString()); } } return null; }
From source file:bd.gov.forms.web.FormBuilder.java
License:Open Source License
@RequestMapping(value = "/pdfExport", method = RequestMethod.GET) public String pdfExport(@RequestParam(value = "formId", required = true) String formId, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "colName", required = false) String colName, @RequestParam(value = "colVal", required = false) String colVal, @RequestParam(value = "sortCol", required = false) String sortCol, @RequestParam(value = "sortDir", required = false) String sortDir, ModelMap model, HttpServletResponse response, HttpServletRequest request) throws IOException { Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // step 2/*www . j av a 2s .c o m*/ try { response.reset(); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "inline; filename=test.pdf"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "No-cache"); PdfWriter writer = PdfWriter.getInstance(document, baos); // step 3 document.open(); Form form = null; //System.out.println("The form id is 1:"+formId); if (formId != null) { form = formDao.getFormWithFields(formId); } if (form != null) { if (form.getStatus() != 2) {//2-active, 3-deactive model.put("doneMessage", "msg.access.denied"); model.put("doneMsgType", "failed"); return "redirect:done.htm"; } initForm(form); } List<Field> fieldList = form.getFields(); if (fieldList.isEmpty()) { System.out.println("The list size is zero"); } PdfPCell space; space = new PdfPCell(); space.setBorder(Rectangle.NO_BORDER); space.setColspan(2); space.setFixedHeight(8); PdfPTable table = new PdfPTable(2); PdfPCell cell; //PdfPCell cell; table.setWidths(new int[] { 1, 2 }); int i = 0; for (Field f : fieldList) { if ("text".equals(f.getType())) { table.addCell(f.getLabel()); cell = new PdfPCell(); cell.setCellEvent(new TextFields(1, i)); table.addCell(cell); } else if ("textarea".equals(f.getType())) { table.addCell(f.getLabel()); cell = new PdfPCell(); cell.setCellEvent(new TextFields(1, i)); cell.setFixedHeight(60); table.addCell(cell); } else if ("select".equals(f.getType())) { table.addCell(f.getType()); cell = new PdfPCell(); cell.setCellEvent(new ChoiceFields(3, f.getList().toArray())); table.addCell(cell); //table.addCell(space); System.out.println("ajsdhd"); } i++; } /* for(Field f : fieldList) { if( "radio".equals(f.getType()) ) { System.out.println("List "+f.getList()+" Oppt"+f.getOptions()+ " df"+f.getColName()); writer = PdfWriter.getInstance(document, new FileOutputStream("TextFieldForm.pdf")); //writer.addJavaScript(Utilities.readFileToString("")); // add the radio buttons PdfContentByte canvas = writer.getDirectContent(); Font font = new Font(FontFamily.HELVETICA, 14); Rectangle rect; PdfFormField field; PdfFormField radiogroup = PdfFormField.createRadioButton(writer, true); radiogroup.setFieldName("language"); RadioCheckField radio; for (int i = 0; i < 2; i++) { rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40); radio = new RadioCheckField(writer, rect, null, f.getLabel()); radio.setBorderColor(GrayColor.GRAYBLACK); radio.setBackgroundColor(GrayColor.GRAYWHITE); radio.setCheckType(RadioCheckField.TYPE_CIRCLE); field = radio.getRadioField(); radiogroup.addKid(field); writer.addAnnotation(field); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(f.getLabel(), font), 70, 790 - i * 40, 0); } //table.addCell(f.getLabel()); //cell = new PdfPCell(); //document.add(radiogroup); //writer.addAnnotation(radiogroup); } } */ // Add submit button PushbuttonField submitBtn = new PushbuttonField(writer, new Rectangle(400, 700, 370, 670), "submitPOST"); //submitBtn.setBackgroundColor(Color.GRAY); submitBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED); submitBtn.setText("Submit"); submitBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT); PdfFormField submitField = submitBtn.getField(); submitField.setAction( PdfAction.createSubmitForm("http://localhost:8084/GovForm-07-02/formBuilder/pdfresponse.htm", null, PdfAction.SUBMIT_HTML_FORMAT)); writer.addAnnotation(submitField); document.add(table); System.out.println("Pdf creation successful"); document.close(); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception ex) { System.out.println("Could not print reasone::" + ex.toString()); } //////////////////////////////////////// email part//////////////////////////// //email functionalities // Recipient's email ID needs to be mentioned. String to = "tanviranik@gmail.com"; // Sender's email ID needs to be mentioned String from = "tanvir_cse@yahoo.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } //////////////////////////////////////// email part//////////////////////////// return null; }
From source file:be.kcbj.placemat.Placemat.java
License:Open Source License
private void createPdf(File file, List<Sponsor> sponsors) throws IOException, DocumentException { System.out.println("Generating PDF file " + file.getAbsolutePath()); Layout layout = new Layout(sponsors); System.out.println("Layout = " + layout); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(file)); document.setPageSize(PageSize.A4.rotate()); document.setMargins(PADDING_DOC, PADDING_DOC, PADDING_DOC, PADDING_DOC); document.open(); PdfPTable table = new PdfPTable(layout.getColumnCount()); table.setWidthPercentage(100);// w w w . j a va 2 s .c o m table.setSpacingBefore(0f); table.setSpacingAfter(0f); for (int i = 0; i < sponsors.size(); i++) { table.addCell(generateCell(sponsors.get(i), layout.getCellHeight())); } for (int i = 0; i < layout.getEmptyCellCount(); i++) { table.addCell(generateCell(new Sponsor(), layout.getCellHeight())); } document.add(table); document.close(); }
From source file:be.rheynaerde.poolsheets.AbstractPoolSheet.java
License:Open Source License
protected void buildSheet() throws DocumentException { Rectangle pageSize = configuration.isLandscape(AbstractPoolSheetConfiguration.TITLE_PAGE) ? PageSize.A4.rotate()/*w ww. java 2s .co m*/ : PageSize.A4; Document document = new Document(pageSize); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); document.addTitle(configuration.getTitle()); document.addCreator(CREATOR); buildTitle(document); buildTable(document); if (configuration.includeOrderOfBouts()) { if (configuration.putBoutOrderOnNewPage()) { pageSize = configuration.isLandscape(AbstractPoolSheetConfiguration.BOUT_ORDER_PAGE) ? PageSize.A4.rotate() : PageSize.A4; document.setPageSize(pageSize); document.newPage(); } buildBoutOrder(document); } document.close(); sheet = baos.toByteArray(); }
From source file:be.rheynaerde.pufmanager.gui.workers.ExportFullPdfWorker.java
License:Open Source License
@Override protected byte[] doInBackground() throws Exception { ByteArrayOutputStream largeBaos = new ByteArrayOutputStream(); Document document = new Document(); PdfCopy copy = new PdfCopy(document, largeBaos); document.open(); String stampText = ResourceBundle .getBundle("be.rheynaerde.pufmanager.gui.export", competition.getSettings().getLocale()) .getString("ExportFullPdf.poolsheet.stamp"); for (int i = 0; i < competition.getRoundCount(); i++) { publish(i);/*from w w w .j a v a 2 s .c o m*/ Round round = competition.getRound(i); int piste = 1; for (Match match : round.getMatches()) { final Match currentMatch = match; ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (match.getRound().includeInternalBouts()) { PufCompletePoolSheetConfiguration config = new NamedPufCompletePoolSheetConfiguration( match.getFirstTeam().getFencerNames(), match.getSecondTeam().getFencerNames(), 20f, competition.getSettings().getImage(), competition.getSettings().getLocale(), competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) { @Override public String getResult(int team1, int player1, int team2, int player2) { Fencer player = (team1 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player1); Fencer opponent = (team2 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player2); PoolResult result = competition.getCompetitionPool().getResult(player, opponent); return result == null ? null : result.toString(); } }; PufCompletePoolSheet sheet = new PufCompletePoolSheet(config); sheet.export(baos); } else { PufTeamPoolSheetConfiguration config = new NamedPufTeamPoolSheetConfiguration( match.getFirstTeam().getFencerNames(), match.getSecondTeam().getFencerNames(), 20f, competition.getSettings().getImage(), competition.getSettings().getLocale(), competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) { @Override public String getResult(int team1, int player1, int team2, int player2) { Fencer player = (team1 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player1); Fencer opponent = (team2 == 0 ? currentMatch.getFirstTeam() : currentMatch.getSecondTeam()).getFencer(player2); PoolResult result = competition.getCompetitionPool().getResult(player, opponent); return result == null ? null : result.toString(); } }; PufTeamPoolSheet sheet = new PufTeamPoolSheet(config); sheet.export(baos); } addPdfToDocument(baos, copy, String.format(stampText, i + 1, piste)); piste++; } if (i == 0) { for (Team team : round.getRestingTeams()) { final Team currentTeam = team; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PufSingleTeamPoolSheetConfiguration config = new NamedPufSingleTeamPoolSheetConfiguration( team.getFencerNames(), 20f, competition.getSettings().getImage(), competition.getSettings().getLocale(), competition.getSettings().getTitle(), competition.getSettings().getSubtitle()) { @Override public String getResult(int player, int opponent) { Fencer playerFencer = currentTeam.getFencer(player); Fencer opponentFencer = currentTeam.getFencer(opponent); PoolResult result = competition.getCompetitionPool().getResult(playerFencer, opponentFencer); return result == null ? null : result.toString(); } }; PufSingleTeamPoolSheet sheet = new PufSingleTeamPoolSheet(config); sheet.export(baos); addPdfToDocument(baos, copy, String.format(stampText, i + 1, piste)); piste++; } } } document.close(); publish(competition.getRoundCount()); return largeBaos.toByteArray(); }
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] createModelPages(Contact contact, List<Model> models, Toc tableOfContents) throws IOException, DocumentException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Document document = iTextUtil.createNewDocument(); PdfWriter writer = PdfWriter.getInstance(document, bos); document.open(); // create a PdfPTable for every model (so we can measure the height) final List<PdfPTable> modelPageTables = new ArrayList<>(); Collections.sort(models);/*w ww .j ava 2s . co m*/ for (Model model : models) { if (model != null) { modelPageTables.add(createModelPage(contact, model, writer)); } } // put the PdfPTable Models tables on PDF pages (multiple per page if possible) byte[] pages = new byte[] {}; int height = 0; List<String> pageNames = new ArrayList<>(); int i = 0; for (PdfPTable modelPageTable : modelPageTables) { // create a new pdf page, if necessary if (height != 0 && (height + modelPageTable.getTotalHeight() + 20 /* for the line separator */ ) >= iTextUtil.PAGE_HEIGHT) { writer.close(); document.close(); bos.close(); byte[] page = bos.toByteArray(); tableOfContents.addEntries(2, pageNames, page, true, Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i)); pages = iTextUtil.merge(pages, page); height = 0; pageNames.clear(); bos = new ByteArrayOutputStream(); document = iTextUtil.createNewDocument(); writer = PdfWriter.getInstance(document, bos); document.open(); } else if (height != 0) { // if not the first model on the page, draw a separator document.add(new Paragraph( new Chunk(new LineSeparator(.25f, 80f, BaseColor.LIGHT_GRAY, Element.ALIGN_CENTER, -2)))); document.add(new Paragraph(new Chunk(" "))); } // rerender the table (with a valid pdfWriter) document.add(createModelPage(contact, models.get(modelPageTables.indexOf(modelPageTable)), writer)); height += modelPageTable.getTotalHeight(); pageNames.add(models.get(modelPageTables.indexOf(modelPageTable)).getProductNameProcessed()); } writer.close(); document.close(); byte[] page = bos.toByteArray(); tableOfContents.addEntries(2, pageNames, page, true, Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i)); pages = iTextUtil.merge(pages, page); return pages; }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
License:Open Source License
public static byte[] merge(byte[]... pdfAsBytes) throws DocumentException, IOException { try (final ByteArrayOutputStream copyBaos = new ByteArrayOutputStream()) { final Document doc = new Document(); final PdfCopy copy = new PdfSmartCopy(doc, copyBaos); doc.open(); int numberOfPages = 0; final java.util.List<HashMap<String, Object>> bookmarks = new ArrayList<>(); PdfReader pdf = null;/*from w ww . j av a 2 s .c o m*/ for (byte[] pdfAsByte : pdfAsBytes) { if (pdfAsByte != null && pdfAsByte.length > 0) { pdf = new PdfReader(pdfAsByte); pdf.consolidateNamedDestinations(); final List<HashMap<String, Object>> pdfBookmarks = SimpleBookmark.getBookmark(pdf); if (!CollectionUtils.isEmpty(pdfBookmarks)) { SimpleBookmark.shiftPageNumbers(pdfBookmarks, numberOfPages, null); bookmarks.addAll(pdfBookmarks); } for (int i = 1; i <= pdf.getNumberOfPages(); i++) { copy.addPage(copy.getImportedPage(pdf, i)); } numberOfPages += pdf.getNumberOfPages(); } } if (pdf != null) { SimpleNamedDestination.getNamedDestination(pdf, false); } if (!CollectionUtils.isEmpty(bookmarks)) { copy.setOutlines(bookmarks); } copy.close(); return copyBaos.toByteArray(); } }