List of usage examples for com.itextpdf.text Font Font
public Font(final FontFamily family, final float size, final int style)
From source file:controller.PdfManager.java
/** * This method will generate an pdf for the applicant * @param email the email of the user//from w w w . j ava 2s .com * @param competences the competences that the applican has added * @param dates the availability periods that the applicant added * @throws IOException */ public void downloadPDF(String email, List<CompetenceProfileDTO> competences, List<String> dates) throws IOException { FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); try { Font font1 = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD); Font font2 = new Font(Font.FontFamily.HELVETICA, 25, Font.UNDERLINE); Font font3 = new Font(Font.FontFamily.HELVETICA, 14); Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); Paragraph h1 = new Paragraph("" + email + " Application", font1); h1.setAlignment(Element.ALIGN_CENTER); document.add(h1); //Add all competences document.add(new Paragraph("Competences", font2)); for (CompetenceProfileDTO s : competences) { document.add(new Paragraph( "Work: " + s.getName() + " Years of Experience: " + s.getYearsOfExperience() + " ", font3)); } document.add(new Paragraph("Availability", font2)); for (String ava : dates) { document.add(new Paragraph("" + ava + "", font3)); } document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setHeader("Content-Disposition", "inline; filename=\"" + email + "\".pdf"); response.setContentType("application/pdf"); // the contentlength response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream OutputStream os = response.getOutputStream(); baos.writeTo(os); os.flush(); os.close(); } catch (DocumentException e) { throw new IOException(e.getMessage()); } }
From source file:controller.Personagem.java
public void GerarPDF(String NomeArq, int nivel) { Document doc = new Document(); if (!NomeArq.endsWith(".pdf")) { NomeArq += ".pdf"; }//from w ww . j av a2 s .c o m Font f_Texto = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL); Font f_Legenda = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL); try { PdfWriter.getInstance(doc, new FileOutputStream(NomeArq)); doc.open(); PdfPTable table = new PdfPTable(24); table.setWidthPercentage(110.0f); table.addCell(Cel(this.getNome(), 12, f_Texto)); table.addCell(Cel(" ", 12, f_Texto)); table.addCell(Cel("Nome do Personagem", 12, f_Legenda)); table.addCell(Cel("Nome do Jogador", 12, f_Legenda)); table.addCell(Cel(nivel + "", 12, f_Texto)); table.addCell(Cel(" ", 4, f_Texto)); table.addCell(Cel(this.getTendencia(), 4, f_Texto)); table.addCell(Cel("", 4, f_Texto)); table.addCell(Cel("Classe e Nvel", 12, f_Legenda)); table.addCell(Cel("Raa", 4, f_Legenda)); table.addCell(Cel("Tendncia", 4, f_Legenda)); table.addCell(Cel("Divindade", 4, f_Legenda)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel(" ", 3, f_Texto)); table.addCell(Cel("Tamanho", 3, f_Legenda)); table.addCell(Cel("Idade", 3, f_Legenda)); table.addCell(Cel("Sexo", 3, f_Legenda)); table.addCell(Cel("Altura", 3, f_Legenda)); table.addCell(Cel("Peso", 3, f_Legenda)); table.addCell(Cel("Olhos", 3, f_Legenda)); table.addCell(Cel("Cabelo", 3, f_Legenda)); table.addCell(Cel("Pele", 3, f_Legenda)); doc.add(table); } catch (DocumentException de) { de.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { doc.close(); } }
From source file:Controller.PrintOrderManagedBean.java
public void executePDF(String maDH) { try {/*from w w w. j a v a 2 s .c om*/ DonHang donhang = new DonHang(); donhang.init(maDH); float CONVERT = 28.346457f;// 1 cm FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); //response.setHeader("Content-disposition","inline; filename=kiran.pdf"); response.setHeader("Pragma", "public"); response.setContentType("application/pdf"); //response.setHeader("Content-Disposition", "attachment;filename=\"ContactList.pdf\""); response.addHeader("Content-disposition", "attachment;filename=\"DataListBean.pdf\""); //step 1: creation of a document-object Document document = new Document(PageSize.A4, 0.5f * CONVERT, 0.5f * CONVERT, 1.0f * CONVERT, 1.0f * CONVERT); //step 2: we create a writer that listens to the document // and directs a PDF-stream to a temporary buffer ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); PdfWriter writer = PdfWriter.getInstance(document, baos); BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf, 18, Font.BOLD); Font font11 = new Font(bf, 11, Font.NORMAL); Font font11_bo = new Font(bf, 11, Font.BOLD); Font font12 = new Font(bf, 12, Font.NORMAL); Font font10 = new Font(bf, 10, Font.NORMAL); Font font9 = new Font(bf, 9, Font.NORMAL); //step 3: we open the document document.open(); PdfPTable tab_Header1; tab_Header1 = new PdfPTable(1); tab_Header1.setWidthPercentage(100); tab_Header1.setHorizontalAlignment(Element.ALIGN_CENTER); PdfPCell cell1; cell1 = new PdfPCell(new Phrase("CNG TY TNHH ABC FASHION", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell( new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S?T: 0909465621", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("?N GIAO HNG", font12)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Bn Bn:", font11_bo)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tn: CNG TY TNHH ABC FASHION", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell( new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S in thoi: 0909465621", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Bn Mua:", font11_bo)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tn: " + donhang.getTenKH(), font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("?a ch: " + donhang.getDiaChiKH(), font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S in thoi: " + donhang.getSoDTKH(), font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Bn Vn chuyn:", font11_bo)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tn:....................................", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("?a ch:...............................", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S in thoi:...............................", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Danh sch hng ha:", font11)); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); ///////////////////////////////bn sn phm float[] crDonHang = { 1.0f * CONVERT, 4.0f * CONVERT, 1.0f * CONVERT, 2.0f * CONVERT, 2.0f * CONVERT }; PdfPTable tab_Header2; tab_Header2 = new PdfPTable(crDonHang.length); tab_Header2.setWidthPercentage(100); tab_Header2.setWidths(crDonHang); tab_Header2.setHorizontalAlignment(Element.ALIGN_CENTER); NumberFormat formatter = new DecimalFormat("#,###,###"); String[] crheader = { "STT", "Tn Hng", "S Lng", "Gi Bn(VN?)", "Thnh Ti?n(VN?)" }; for (int i = 0; i < crheader.length; i++) { PdfPCell cell = new PdfPCell(new Phrase(crheader[i], font11)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tab_Header2.addCell(cell); } int stt = 1; for (SanPhamDH sp : donhang.getListSP()) { PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(stt), font11)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(sp.getTenSP(), font11)); cell.setHorizontalAlignment(Element.ALIGN_LEFT); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(sp.getSoluong(), font11)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getGiaSP())), font11)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); tab_Header2.addCell(cell); cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getThanhTien())), font11)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); tab_Header2.addCell(cell); stt++; } cell1 = new PdfPCell(tab_Header2); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tng ti?n hng: " + formatter.format( Double.parseDouble(donhang.getTienTamTinh() == null ? "0" : donhang.getTienTamTinh())) + " VN?", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tng ti?n vn chuyn: " + formatter.format(Double .parseDouble(donhang.getTienVanChuyen() == null ? "0" : donhang.getTienVanChuyen())) + " VN?", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("Tng ti?n thanh ton: " + formatter.format(Double.parseDouble(donhang.getTongTien())) + " VN?", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("S ti?n thanh ton bng ch: " + DocTien.doctien(donhang.getTongTien().replaceAll(" ", "")) + "ng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase(" ", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase("TP H Ch Minh, ngy thng nm ", font11)); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setPaddingRight(1.0f * CONVERT); cell1.setBorder(0); tab_Header1.addCell(cell1); cell1 = new PdfPCell(new Phrase(" ", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header1.addCell(cell1); PdfPTable tab_Header3; tab_Header3 = new PdfPTable(3); tab_Header3.setWidthPercentage(100); tab_Header3.setHorizontalAlignment(Element.ALIGN_CENTER); cell1 = new PdfPCell(new Phrase("Ng?i nhn hng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("Ng?i giao hng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("Ng?i bn hng", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11)); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setPaddingBottom(5.0f); cell1.setBorder(0); tab_Header3.addCell(cell1); cell1 = new PdfPCell(tab_Header3); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setBorder(0); tab_Header1.addCell(cell1); document.add(tab_Header1); document.close(); //step 6: we output the writer as bytes to the response output // the contentlength is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); baos.flush(); faces.responseComplete(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Controller.Receipt.Controller_FXML_Receipt.java
public void createReceipt(String filename, String patientid) throws DocumentException, IOException, PrinterException { {//from w w w .j a v a 2s . c o m //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. Document document = new Document(); String receipt_id = null; String patientname = null; String date = null; String total_sum = null; try { try { PdfWriter.getInstance(document, new FileOutputStream(filename)); } catch (FileNotFoundException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } } catch (DocumentException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } document.open(); Font font = new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD); //getFont("c:/windows/fonts/Shruti.ttf", //BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); //document.add(new Paragraph("english",font)); com.itextpdf.text.Image img = null; // try { // img = com.itextpdf.text.Image.getInstance("C:"); // img.scalePercent(80f); // } catch (BadElementException ex) { // Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); // } catch (IOException ex) { // Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); // } /*try { document.add(img); } catch (DocumentException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); }*/ Paragraph title = new Paragraph("RECEIPT", font); Paragraph header = new Paragraph("SHARDA HOSPITAL"); header.setAlignment(Element.ALIGN_CENTER); title.setAlignment(Element.ALIGN_CENTER); Paragraph receiptid = new Paragraph("R.No" + receipt_id, font); receiptid.setAlignment(Element.ALIGN_LEFT); Paragraph Date = new Paragraph("Date :" + date, font); Date.setAlignment(Element.ALIGN_RIGHT); try { document.add(header); } catch (DocumentException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } try { document.add(title); } catch (DocumentException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } try { document.add(receiptid); } catch (DocumentException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } try { document.add(Date); } catch (DocumentException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } String DOJ = null; String diagnosis = null; String no_of_days = null; String DOD = null; Paragraph patient_details = new Paragraph("Received " + total_sum + "from Mr./Mrs. " + patientname + " towards indoor/outdoor charges detailed as below." + " He/She was admitted in hospital/under treatment from" + DOJ + "to " + DOD + ". He/She is suffering from " + diagnosis + "." + " He/She has to take future medicie for" + no_of_days + ".", font); try { document.add(patient_details); } catch (DocumentException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Chaitanya"); Object newValue = null; //Check whether item is selected and set value of selected item to Label if (table.getSelectionModel().getSelectedItem() != null) { TableView.TableViewSelectionModel selectionModel = table.getSelectionModel(); ObservableList selectedCells = selectionModel.getSelectedCells(); TablePosition tablePosition = (TablePosition) selectedCells.get(0); Object val1 = tablePosition.getTableColumn().getCellData(newValue); System.out.println("Fee Type Value" + val1); TablePosition tablePosition1 = (TablePosition) selectedCells.get(1); Object val2 = tablePosition1.getTableColumn().getCellData(newValue); System.out.println("Charges Value" + val2); } document.close(); String pdfFile = "report.pdf"; try { printPDF(pdfFile); } catch (IOException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } catch (PrinterException ex) { Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:Controllers.ExportController.java
public static void exportExam(String path) { model = (DefaultTableModel) tableExam.getModel(); int selectRow = tableExam.getSelectedRow(); if (selectRow != -1) { int idExam = (int) model.getValueAt(selectRow, 0) - 1; exams = ExamModel.readExam();/*from w w w . j a va 2 s .c o m*/ Exam ex = exams.getExam(idExam); try { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(path)); document.open(); BaseFont f = BaseFont.createFont("/font/vuArial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font titleExamFont = new Font(f, 25.0f, Font.BOLD); Font titlePartFont = new Font(f, 18.0f, Font.BOLD); Font headFont = new Font(f, 13.0f, Font.BOLD); Font suggestionFont = new Font(f, 13.0f, Font.ITALIC); Font contentFont = new Font(f, 13.0f, Font.NORMAL); Paragraph align = new Paragraph(" "); Paragraph title = new Paragraph(ex.getNameExam(), titleExamFont); title.setAlignment(Paragraph.ALIGN_CENTER); document.add(title); document.add(align); ArrayList<Question> question = ex.getQuestions(); boolean haveMultipleChoice = false; boolean haveEssay = false; // Kim tra xem c phn t lun khng for (Question q : question) { if (q instanceof Essay) { haveEssay = true; } // Kim tra xem c phn trc nghim khng} else { haveMultipleChoice = true; } if (haveEssay && haveMultipleChoice) break; } int count; if (haveMultipleChoice) { count = 0; Paragraph titlePart = new Paragraph("Trc nghim", titlePartFont); document.add(align); document.add(titlePart); document.add(align); for (Question q : question) if (q instanceof MultipleChoice) { count++; Phrase numberQuestion = new Phrase("Cu " + count + ": ", headFont); Phrase contentQuestion = new Phrase(q.getContentQuestion(), contentFont); Paragraph questionParagraph = new Paragraph(); questionParagraph.add(numberQuestion); questionParagraph.add(contentQuestion); document.add(questionParagraph); MultipleChoice mc = (MultipleChoice) q; ArrayList<Answer> answers = mc.getAnswers(); boolean ok = true; for (int i = 0; i < answers.size(); ++i) { Answer answer = answers.get(i); if (answer.getContentAnswer().length() > 30) ok = false; } if (ok == true) { PdfPTable table = new PdfPTable(2); for (int i = 0; i < answers.size(); ++i) { Answer answer = answers.get(i); PdfPCell answerParagraph = new PdfPCell(new Paragraph( (char) (65 + i) + ". " + answer.getContentAnswer(), contentFont)); answerParagraph.setBorder(Rectangle.NO_BORDER); table.addCell(answerParagraph); } document.add(table); } else { PdfPTable table = new PdfPTable(1); for (int i = 0; i < answers.size(); ++i) { Answer answer = answers.get(i); PdfPCell answerParagraph = new PdfPCell(new Paragraph( (char) (65 + i) + ". " + answer.getContentAnswer(), contentFont)); answerParagraph.setBorder(Rectangle.NO_BORDER); table.addCell(answerParagraph); } document.add(table); } } } if (haveEssay) { count = 0; Paragraph titlePart = new Paragraph("T Lun", titlePartFont); document.add(align); document.add(titlePart); document.add(align); for (Question q : question) if (q instanceof Essay) { count++; Phrase numberQuestion = new Phrase("Cu " + count + ": ", headFont); Phrase contentQuestion = new Phrase(q.getContentQuestion(), contentFont); Paragraph questionParagraph = new Paragraph(); questionParagraph.add(numberQuestion); questionParagraph.add(contentQuestion); Essay es = (Essay) q; Phrase headerSuggestion = new Phrase("Gi : ", suggestionFont); Phrase contentSuggestion = new Phrase(es.getSuggest(), contentFont); Paragraph suggestion = new Paragraph(); suggestion.add(headerSuggestion); suggestion.add(contentSuggestion); document.add(questionParagraph); document.add(suggestion); } } document.close(); } catch (FileNotFoundException exp) { exp.printStackTrace(); } catch (DocumentException exp) { exp.printStackTrace(); } catch (IOException exp) { exp.printStackTrace(); } } }
From source file:cv.mikusher.outros.exemploescola.PrimeiroPDF.java
License:Open Source License
public static void main(String[] args) throws Exception { Document doc = null;//from w w w . j a v a 2 s . co m OutputStream os = null; try { doc = new Document(PageSize.A4, 72, 72, 72, 72); os = new FileOutputStream("C://outPdf.pdf"); PdfWriter.getInstance(doc, os); doc.open(); Font ftT = new Font(Font.FontFamily.COURIER, 20, Font.BOLD); Paragraph pr_1 = new Paragraph("Meu primeiro arquivo PDF.", ftT); doc.add(pr_1); Paragraph pr_2 = new Paragraph("Ola mundo, um documento PDF criado em JAVA"); doc.add(pr_2); //Image img = Image.getInstance("mikusher.jpg"); //img.setAlignment(Element.ALIGN_CENTER); //doc.add(img); } finally { if (doc != null) { doc.close(); } if (os != null) { os.close(); } } }
From source file:de.domjos.schooltools.core.utils.fileUtils.PDFBuilder.java
License:Open Source License
public void addTable(List<String> headers, float[] headerWidth, List<List<Map.Entry<String, BaseColor>>> cells) throws Exception { PdfPTable table = new PdfPTable(headers.size()); if (headerWidth != null) { table.setWidths(headerWidth);//from www . j a v a 2 s .c o m } for (String header : headers) { PdfPCell cell = new PdfPCell( new Phrase(header, new Font(Font.FontFamily.HELVETICA, 18, Font.BOLDITALIC))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); table.addCell(cell); } for (List<Map.Entry<String, BaseColor>> row : cells) { for (Map.Entry<String, BaseColor> cellItem : row) { PdfPCell cell = new PdfPCell( new Phrase(cellItem.getKey(), new Font(Font.FontFamily.HELVETICA, 14, Font.NORMAL))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBackgroundColor(cellItem.getValue()); table.addCell(cell); } } this.document.add(table); }
From source file:de.tuttas.servlets.DokuServlet.java
private Document createUmfrageauswertung(List<UmfrageResult> res1, List<UmfrageResult> res2, int idUmfrage1, int idUmfrage2, String filter1, String filter2, String kopf, OutputStream out) throws DocumentException, BadElementException, IOException { Document document = new Document(); /* Basic PDF Creation inside servlet */ Umfrage u1 = em.find(Umfrage.class, idUmfrage1); Umfrage u2 = em.find(Umfrage.class, idUmfrage2); // Bild einfgen String url = "http://www.mmbbs.de/fileadmin/template/mmbbs/gfx/mmbbs_logo_druck.gif"; Image image = Image.getInstance(url); image.setAbsolutePosition(45f, 720f); image.scalePercent(50f);//from ww w . ja v a2 s . com StringBuilder htmlString = new StringBuilder(); htmlString.append(kopf); htmlString.append("<br></br>"); int maxRows = res1.size(); if (res2.size() > maxRows) { maxRows = res2.size(); } PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); writer.setPageEmpty(false); Font boldFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD); Font normalFont = new Font(Font.FontFamily.HELVETICA, 10, Font.ITALIC); PdfPTable table = new PdfPTable(new float[] { 1, 2, 2 }); PdfPCell qestionCell; PdfPCell group1Cell; PdfPCell group2Cell; int i = 0; for (i = 0; i < maxRows; i++) { Log.d("Print Row " + i); if (i % 5 == 0) { if (i != 0) { document.add(table); document.newPage(); document = printHead(writer, document, htmlString, out, image); } else { document = printHead(writer, document, htmlString, out, image); } table = new PdfPTable(new float[] { 1, 2, 2 }); table.setWidthPercentage((float) 100.0); qestionCell = new PdfPCell(new Phrase("\nFragen", boldFont)); group1Cell = new PdfPCell(); group1Cell.addElement(new Phrase("Hauptgruppe:", boldFont)); group1Cell.addElement(new Phrase(u1.getNAME() + "\n" + filter1, normalFont)); group2Cell = new PdfPCell(); group2Cell.addElement(new Phrase("Vergleichsgruppe:", boldFont)); group2Cell.addElement(new Phrase(u2.getNAME() + "\n" + filter2, normalFont)); qestionCell.setBorderWidth(2.0f); group1Cell.setBorderWidth(2.0f); group2Cell.setBorderWidth(2.0f); table.addCell(qestionCell); table.addCell(group1Cell); table.addCell(group2Cell); } String url1 = UmfrageUtil.getCharUrl(res1.get(i)); Log.d("URL1=" + url1); Image image1 = Image.getInstance(url1); Image image2 = null; if (res2.size() > i) { String url2 = UmfrageUtil.getCharUrl(res2.get(i)); Log.d("URL2=" + url2); image2 = Image.getInstance(url2); } Log.d("Write to pdf:" + res1.get(i).getFrage()); qestionCell = new PdfPCell(new Phrase(res1.get(i).getFrage(), normalFont)); qestionCell.setBorderWidth(1.0f); group1Cell = new PdfPCell(image1, true); group1Cell.setBorderWidth(1.0f); group1Cell.setPadding(10); if (image2 != null) group2Cell = new PdfPCell(image2, true); else group2Cell = new PdfPCell(); group2Cell.setBorderWidth(1.0f); group2Cell.setPadding(10); table.addCell(qestionCell); table.addCell(group1Cell); table.addCell(group2Cell); } if (!(i % 5 == 0)) { document.add(table); } document.close(); return document; }
From source file:documentos.PlanillaServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . j a va2 s.c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { response.setContentType("application/pdf"); Connection conexion = null; HttpSession session = request.getSession(true); try { conexion = ds.getConnection(); edificioDAO edifDAO = new edificioDAO(); edifDAO.setConexion(conexion); usuarioDAO usuDAO = new usuarioDAO(); usuDAO.setConexion(conexion); //obtener variable boolean error = false; String idString = (String) request.getParameter("id_edificio"); int idEdificio = 0; try { idEdificio = Integer.parseInt(idString); } catch (Exception ex) { System.out.println("Error al convertir variables :" + ex); error = true; } //obtener datos de edificio segun el id edificio edif = new edificio(); edif = edifDAO.findbyIdEdificio(idEdificio); DetalleEdificioDAO detEdifDAO = new DetalleEdificioDAO(); detEdifDAO.setConexion(conexion); administradorDAO adminDAO = new administradorDAO(); adminDAO.setConexion(conexion); //obtener admin Edificio administrador admin = new administrador(); admin = adminDAO.findbyIdEdificio(idEdificio); //obtener datos de detalleEdif detalleEdificio detalleEdif = new detalleEdificio(); detalleEdif = detEdifDAO.findbyIdEdificio(idEdificio); //obtener datos de usuario segun id edificio usuario usuario = new usuario(); usuario = usuDAO.findbyIdUsuarios(edif.getIdUsuario()); //guardar datos de edif en variables separadas String nombreVendedor = usuario.getNombre(); String apellidoVendedor = usuario.getApellido(); int annoNorma = edif.getAnoEdificio(); String ubicacionMed = detalleEdif.getUbicacionMedidores(); String ciige = detalleEdif.getCiigeAnterior(); String testDePruebas = detalleEdif.getDespiche(); String nombreEdif = edif.getNombreEdificio(); String correo = admin.getEmailAdmin(); String fonoAdmin = admin.getTelefonoAdmin(); String fonoEdif = edif.getTelefonoEdificio(); String rutEdif = edif.getRutEdificio(); String dirEdif = edif.getDireccionEdificio(); String nomAdmin = admin.getNombreAdmin(); String rutAdmin = admin.getRutAdmin(); int cantidadDe = edif.getCantCasas() + edif.getCantDepartamentos() + edif.getCantLocales() + edif.getCantLavanderias(); int cantPisos = edif.getCantPisos(); int idEmpresaGas = edif.getIdGas(); //determinar el nombre de la empresa de gas segun su id String empresagas = ""; if (idEmpresaGas == 1) { empresagas = "GASVALPO"; } if (idEmpresaGas == 2) { empresagas = "LIPIGAS"; } if (idEmpresaGas == 3) { empresagas = "ABASTIBLE"; } if (idEmpresaGas == 4) { empresagas = "GASCO"; } if (idEmpresaGas == 5) { empresagas = "OTROS"; } int annoEdif = edif.getAnoEdificio(); int potencia = edif.getPotenciaReal(); int cantidaConductos = edif.getCantConductos(); int cantidadCalderas = edif.getCantCalderas(); //Crear documento Document document = new Document(); Image logo = Image.getInstance(getClass().getResource("logo.png")); PdfWriter.getInstance(document, response.getOutputStream()); Font fuenteNegrita = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD); Font fuenteNormal = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL); Font fuenteEPiePagina = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.BOLD); Font fuentePiePagina = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD); // step 3 document.open(); // step 4 logo.setAbsolutePosition(270f, 750f); logo.scalePercent(65f); PdfPTable tablaEncabezado = new PdfPTable(2); PdfPTable tablaContenido = new PdfPTable(2); tablaEncabezado.addCell(new Paragraph("PLANILLA CIIG-e INSPECCIN PERIODICA")); tablaEncabezado.addCell(logo); tablaContenido.setSpacingBefore(15); tablaContenido.setSpacingAfter(20); tablaContenido.addCell(new Paragraph("VENDEDORA", fuenteNormal)); tablaContenido.addCell(new Paragraph(nombreVendedor + " " + apellidoVendedor, fuenteNormal)); tablaContenido.addCell(new Paragraph("AO DEL EDIFICIO Y NORMA APLICAR", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(annoEdif), fuenteNormal)); tablaContenido .addCell(new Paragraph("UBICACIN MEDIDORES: EN LOS PISOS, FUERA DEL EDIFICO", fuenteNormal)); tablaContenido.addCell(new Paragraph(ubicacionMed, fuenteNormal)); tablaContenido .addCell(new Paragraph("NRO CIIGE DE LA INSPECCION ANTERIOR (VER PAGINA SEC)", fuenteNormal)); tablaContenido.addCell(new Paragraph(ciige, fuenteNormal)); tablaContenido.addCell(new Paragraph("T DE PRUEBAS, DESPICHE OTRO (COCINA)", fuenteNormal)); tablaContenido.addCell(new Paragraph(testDePruebas, fuenteNormal)); tablaContenido.addCell(new Paragraph("NOMBRE: EDIFICIO, CONDOMINIO, PROPIETARIO, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(nombreEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("CORREO ELECTRONICO", fuenteNormal)); tablaContenido.addCell(new Paragraph(correo, fuenteNormal)); tablaContenido.addCell(new Paragraph("FONO ADMINISTRADOR /FONO EDIFICIO", fuenteNormal)); tablaContenido.addCell(new Paragraph("Fono Administrador :" + fonoAdmin + " Fono Edificio :" + fonoEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("R.U.T EDIFICIO, CONDOMINIO, PROPIETARIOS, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(rutEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("DIRECCIN DEL EDIFICO", fuenteNormal)); tablaContenido.addCell(new Paragraph(dirEdif, fuenteNormal)); tablaContenido.addCell(new Paragraph("NOMBRE ADMINISTRADOR, PROPIETARIO, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(nomAdmin, fuenteNormal)); tablaContenido.addCell(new Paragraph("RUT: ADMINISTRADOR, PROPIETARIO, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(rutAdmin, fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE: DEPTOS, CASAS, LOCALES, ETC.", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidadDe), fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE PISOS INMUEBLE", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantPisos), fuenteNormal)); tablaContenido.addCell(new Paragraph("EMPRESA DISTRIBUIDORA DE GAS", fuenteNormal)); tablaContenido.addCell(new Paragraph(empresagas, fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE INSTALACIONES", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidadDe), fuenteNormal)); tablaContenido.addCell(new Paragraph("TIPO DE ARTEFACTOS INSTALADOS", fuenteNormal)); tablaContenido.addCell(new Paragraph("", fuenteNormal)); tablaContenido.addCell(new Paragraph("POTENCIA TOTAL INSTALADA", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(potencia), fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE CONDUCTOS COLECTIVOS", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidaConductos), fuenteNormal)); tablaContenido.addCell(new Paragraph("CANTIDAD DE CALDERAS CENTRALES", fuenteNormal)); tablaContenido.addCell(new Paragraph(Integer.toString(cantidadCalderas), fuenteNormal)); document.add(tablaEncabezado); document.add(tablaContenido); Paragraph textoIng = new Paragraph("IngeneriaRSLimitada", fuenteEPiePagina); textoIng.setAlignment(Element.ALIGN_CENTER); Paragraph textPie = new Paragraph( "Calle Montaa 754 Oficina 37-A Via Del Mar / ingenieria.sr@gmail.com - Fono 032-2697175 / 92564059", fuentePiePagina); textPie.setAlignment(Element.ALIGN_CENTER); document.add(textoIng); document.add(textPie); document.close(); } catch (DocumentException de) { throw new IOException(de.getMessage()); } }
From source file:ECS.create.java
create() { //geting the file path from Page. String dpath = Page.dpath;//from ww w . j a va 2 s . c o m try { //define program "information" as data information data = new information(); //crate a PDF File Document cs = new Document(); //locate where the PDF save. FileOutputStream local = new FileOutputStream(dpath); //New PDF location PdfWriter writer = PdfWriter.getInstance(cs, local); //Edit Propety of the PDF cs.addTitle("Title@CoverSheet"); cs.addAuthor("Author@rensanning"); cs.addSubject("Subject@iText sample"); cs.addKeywords("Keywords@iText"); cs.addCreator("Creator@iText"); //Seting the Font of the text in the PDF Font title = new Font(Font.FontFamily.HELVETICA, 25, Font.BOLD); //Font stitle = new Font(Font.FontFamily.COURIER, 18,Font.ITALIC | Font.UNDERLINE); Font stitle = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); Font usual = new Font(Font.FontFamily.TIMES_ROMAN, 18); // open the PDF File cs.open(); PdfContentByte canvas = writer.getDirectContent(); // insert the information in the PDF //group the information into paragrph Paragraph sinfo = new Paragraph(); //using the data form the database which geting by program "information" sinfo.add(new Chunk("Name: " + data.fn + " " + data.ln, title)); //cs.add(Chunk.NEWLINE); sinfo.add(new Chunk(" ")); sinfo.add(new Chunk("SID: " + data.sid, title)); sinfo.setLeading(40); //sinfo.add(Chunk.NEWLINE); cs.add(sinfo); Paragraph cinfo = new Paragraph(); cinfo.add(new Chunk("Course: " + data.cid + " " + data.cn, stitle)); cinfo.setLeading(30); cinfo.add(Chunk.NEWLINE); cs.add(cinfo); Paragraph minfo = new Paragraph(); minfo.add(new Chunk("Module: ", stitle)); minfo.add(new Chunk(data.mid + " " + data.mn, usual)); minfo.setLeading(30); minfo.add(Chunk.NEWLINE); cs.add(minfo); // insert the information in the PDF Paragraph cwinfo = new Paragraph(); cwinfo.add(new Chunk("Coursework ID: ", stitle)); cwinfo.add(new Chunk(data.cwid, usual)); cwinfo.add(Chunk.NEWLINE); cwinfo.add(new Chunk("Coursework Tile: ", stitle)); cwinfo.add(new Chunk(data.cwt, usual)); cwinfo.add(Chunk.NEWLINE); cwinfo.add(new Chunk("Coursework Deadline is on ", stitle)); cwinfo.add(new Chunk(data.cwed, usual)); cwinfo.setLeading(30); cs.add(cwinfo); cs.add(new Paragraph("Rule: \n" + " I am the Boss", usual)); //Phrase phrase1= new Phrase("This is sentence 1. ", title); //ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase1, 30, 600, 0); //cs.add(new Paragraph("Name: " + data.fn + " " + data.ln, title)); //cs.add(new Chunk("SID: " + data.sid)); //Close the PDF file cs.close(); } catch (DocumentException | FileNotFoundException ex) { System.out.println(ex); } }