List of usage examples for com.itextpdf.text Image setAbsolutePosition
public void setAbsolutePosition(final float absoluteX, final float absoluteY)
Image
. From source file:bussiness.ReportHandler.java
public void BuildSaleReport(double totalCost) { try {// w ww . j a v a2s .c o m // Se crea el documento Document documento = new Document(); // Se crea el OutputStream para el fichero donde queremos dejar el pdf. FileOutputStream ficheroPdf = new FileOutputStream("fichero.pdf"); // Se asocia el documento al OutputStream y se indica que el espaciado entre // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20); Image imagen = Image.getInstance("logo.jpeg"); documento.open(); PdfPTable table = new PdfPTable(2); table.getDefaultCell().setBorder(PdfPCell.NO_BORDER); table.getDefaultCell().setPaddingLeft(60); BuildHeaderSaleReport(documento); documento.add(new Chunk("\n")); documento.add(new Chunk("\n")); documento.add(new Chunk("\n")); documento.add(new Chunk("\n")); documento.add(new Chunk("\n")); documento.add(new Chunk("\n")); imagen.setAbsolutePosition(110f, 150f); BuildBodySaleReport(table, totalCost, documento); BuildFooterSaleReport(documento); documento.add(imagen); documento.close(); } catch (Exception e) { System.err.println("Ocurrio un error: " + e); System.exit(-1); } }
From source file:bussiness.ReportHandler.java
public void BuildVeterinaryPrescription(String clientName, String petName, List<Medicine> medicines, String comments, Double totalCost) { try {/*from w w w . ja v a 2 s. c o m*/ Document veterinaryPrescription = new Document(PageSize.A3.rotate()); //Tal vez agregar la fecha al nombre de la receta FileOutputStream fileOutputStream = new FileOutputStream("prescription.pdf"); PdfWriter.getInstance(veterinaryPrescription, fileOutputStream).setInitialLeading(20); Image logo = Image.getInstance("logo2.png"); Image division = Image.getInstance("linea.png"); veterinaryPrescription.open(); division.setAbsolutePosition(20f, 600f); veterinaryPrescription.add(division); logo.setAbsolutePosition(400, 50f); veterinaryPrescription.add(logo); //Encabezado BuildHeaderPrescription(veterinaryPrescription, clientName, petName); //Cuerpo veterinaryPrescription.add(new Chunk("\n")); veterinaryPrescription.add(new Chunk("\n")); veterinaryPrescription.add(new Chunk("\n")); PdfPTable table = new PdfPTable(3); table.getDefaultCell().setBorder(PdfPCell.NO_BORDER); table.getDefaultCell().setPaddingLeft(60); BuildBodyPrescription(medicines, veterinaryPrescription, totalCost, table); BuildFooterPrescription(veterinaryPrescription, comments); veterinaryPrescription.close(); } catch (Exception e) { System.err.println("Ocurrio un error: " + e); System.exit(-1); } }
From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java
public String createInvoicePDF(String imagePath, String OUTPUT_FILEPATH) throws FileNotFoundException, IOException, DocumentException, InterruptedException, URISyntaxException { float currPosition = 0; String sFilepath = OUTPUT_FILEPATH; Image image = Image.getInstance(imagePath); //create a paragraph Paragraph paragraph = new Paragraph(); Document d = new Document(PageSize.A4_LANDSCAPE.rotate()); PdfWriter w = PdfWriter.getInstance(d, new FileOutputStream(sFilepath)); d.open();//from ww w .j av a 2s. c om PdfContentByte cb = w.getDirectContent(); ByteArrayOutputStream stampedBuffer; URL resource = this.getClass().getClassLoader().getResource(ShippingConstants.INVOICE_TEMPLATE); File file = new File(resource.toURI()); PdfReader templateReader = new PdfReader(new FileInputStream(file)); stampedBuffer = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(templateReader, stampedBuffer); stamper.setFormFlattening(true); AcroFields form = stamper.getAcroFields(); float[] columnWidths = { 1f, 1f, 1f, 3f }; //create PDF table with the given widths PdfPTable table = new PdfPTable(columnWidths); // form.setField("field1", String.format("Form Text %d", i+1)); form.setField("OBName", "Ragav"); form.setField("OBCompany", "Ragav"); form.setField("OBAddress", "2002 SW Sarazen Cr"); form.setField("OBCity", "Bentonville"); form.setField("OBPhone", "1234567890"); form.setField("STName", "Ragav"); form.setField("STCompany", "Ragav"); form.setField("STAddress", "2002 SW Sarazen Cr"); form.setField("STCity", "Bentonville"); form.setField("STPhone", "1234567890"); form.setField("itemNo", "12334535"); form.setField("itemDesc", "Laundry Bag"); stamper.close(); templateReader.close(); form = null; stamper.close(); templateReader.close(); PdfReader stampedReader = new PdfReader(stampedBuffer.toByteArray()); PdfImportedPage page = w.getImportedPage(stampedReader, 1); cb.addTemplate(page, 0, currPosition); image.scaleAbsoluteHeight(325); image.scaleAbsoluteWidth(550); image.setRotationDegrees(270); image.setAbsolutePosition(450, 20); d.add(image); d.close(); w.close(); return sFilepath; }
From source file:com.education.freelancer.MainActivity.java
private void setSignatureStamp(PdfStamper stamper, AcroFields acroFields, String signId) { String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/DigitSign/"; String StoredPath = DIRECTORY + signId + ".png"; AcroFields.FieldPosition f = acroFields.getFieldPositions(signId).get(0); int page = f.page; Rectangle rect = f.position;//from w w w .j av a 2 s . com File imgFile = new File(StoredPath); Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); if (myBitmap == null) { return; } // myBitmap=getResizedBitmap(myBitmap,160); ByteArrayOutputStream stream = new ByteArrayOutputStream(); myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); Image img = null; try { img = Image.getInstance(stream.toByteArray()); img.scaleToFit(rect.getWidth(), rect.getHeight()); img.setAbsolutePosition(rect.getLeft(), rect.getBottom()); stamper.getOverContent(page).addImage(img); imgFile.delete(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java
License:Open Source License
/** * The <code>addImageToPdf</code> method is used to add image to pdf and make it searchable by adding image text in invisible mode * w.r.t parameter 'isPdfSearchable' passed. * //from w ww. j a v a2s . co m * @param pdfWriter {@link PdfWriter} writer of pdf in which image has to be added * @param htmlUrl {@link HocrPage} corresponding html file for fetching text and coordinates * @param imageUrl {@link String} url of image to be added in pdf * @param isPdfSearchable true for searchable pdf else otherwise * @param widthOfLine */ private void addImageToPdf(PdfWriter pdfWriter, HocrPage hocrPage, String imageUrl, boolean isPdfSearchable, final int widthOfLine) { if (null != pdfWriter && null != imageUrl && imageUrl.length() > 0) { try { LOGGER.info("Adding image" + imageUrl + " to pdf using iText"); Image pageImage = Image.getInstance(imageUrl); float dotsPerPointX = pageImage.getDpiX() / PDF_RESOLUTION; float dotsPerPointY = pageImage.getDpiY() / PDF_RESOLUTION; PdfContentByte pdfContentByte = pdfWriter.getDirectContent(); pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY); pageImage.setAbsolutePosition(0, 0); // Add image to pdf pdfWriter.getDirectContentUnder().addImage(pageImage); pdfWriter.getDirectContentUnder().add(pdfContentByte); // If pdf is to be made searchable if (isPdfSearchable) { LOGGER.info("Adding invisible text for image: " + imageUrl); float pageImagePixelHeight = pageImage.getHeight(); Font defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK); // Fetch text and coordinates for image to be added Map<String, int[]> textCoordinatesMap = getTextWithCoordinatesMap(hocrPage, widthOfLine); Set<String> ketSet = textCoordinatesMap.keySet(); // Add text at specific location for (String key : ketSet) { int[] coordinates = textCoordinatesMap.get(key); float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX; float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY; pdfContentByte.beginText(); // To make text added as invisible pdfContentByte.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); pdfContentByte.setLineWidth(Math.round(bboxWidthPt)); // Ceil is used so that minimum font of any text is 1 // For exception of unbalanced beginText() and endText() if (bboxHeightPt > 0.0) { pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), (float) Math.ceil(bboxHeightPt)); } else { pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), 1); } float xCoordinate = (float) (coordinates[0] / dotsPerPointX); float yCoordinate = (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY); pdfContentByte.moveText(xCoordinate, yCoordinate); pdfContentByte.showText(key); pdfContentByte.endText(); } } pdfContentByte.closePath(); } catch (BadElementException badElementException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + badElementException.toString()); } catch (DocumentException documentException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + documentException.toString()); } catch (MalformedURLException malformedURLException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + malformedURLException.toString()); } catch (IOException ioException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + ioException.toString()); } } }
From source file:com.etest.pdfgenerator.InventoryCasesReportPDF.java
public InventoryCasesReportPDF() { Document document = null;/*from w ww .j a va2s. co m*/ Date date = new Date(); try { document = new Document(PageSize.LETTER, 50, 50, 50, 50); PdfWriter.getInstance(document, outputStream); document.open(); Font header = FontFactory.getFont("Times-Roman", 12, Font.BOLD); Font content = FontFactory.getFont("Times-Roman", 10); Font dateFont = FontFactory.getFont("Times-Roman", 8); Image img = null; try { img = Image.getInstance("C:\\eTest-images\\SUCN_seal.png"); img.scaleToFit(60, 60); img.setAbsolutePosition(500, 700); } catch (BadElementException | IOException ex) { Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex); } document.add(img); Paragraph reportTitle = new Paragraph(); reportTitle.setAlignment(Element.ALIGN_CENTER); reportTitle.add(new Phrase("Inventory of Cases Report", header)); document.add(reportTitle); Paragraph datePrinted = new Paragraph(); datePrinted.setSpacingAfter(20f); datePrinted.setAlignment(Element.ALIGN_CENTER); datePrinted.add( new Phrase("Date printed: " + new SimpleDateFormat("dd MMMM yyyy").format(date), dateFont)); document.add(datePrinted); PdfPTable table = new PdfPTable(4); table.setWidthPercentage(100); table.setWidths(new int[] { 100, 300, 100, 100 }); table.setSpacingAfter(5f); PdfPCell cellOne = new PdfPCell(new Phrase("Subject")); cellOne.setBorder(Rectangle.NO_BORDER); cellOne.setPaddingLeft(10); cellOne.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cellOne.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellTwo = new PdfPCell(new Phrase("Descriptive Title")); cellTwo.setBorder(Rectangle.NO_BORDER); cellTwo.setPaddingLeft(10); cellTwo.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cellTwo.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellThree = new PdfPCell(new Phrase("No. of Cases")); cellThree.setBorder(Rectangle.NO_BORDER); cellThree.setPaddingLeft(10); cellThree.setHorizontalAlignment(Element.ALIGN_CENTER); cellThree.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellFour = new PdfPCell(new Phrase("No. of Items")); cellFour.setBorder(Rectangle.NO_BORDER); cellFour.setPaddingLeft(10); cellFour.setHorizontalAlignment(Element.ALIGN_CENTER); cellFour.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cellOne); table.addCell(cellTwo); table.addCell(cellThree); table.addCell(cellFour); table.getDefaultCell().setBorderWidth(0f); document.add(table); for (InventoryOfCasesReport report : service.getInventoryOfCases()) { PdfPTable table2 = new PdfPTable(4); table2.setWidthPercentage(100); table2.setWidths(new int[] { 100, 300, 100, 100 }); table2.setSpacingBefore(3f); table2.setSpacingAfter(3f); if (!service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()).isEmpty()) { if (!service .getListOfCellCaseIdBySyllabusId( service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId())) .isEmpty()) { PdfPCell cell1 = new PdfPCell(new Paragraph(report.getSubject(), content)); cell1.setBorder(0); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell(new Paragraph(report.getDescriptiveTitle(), content)); cell2.setBorder(0); cell2.setPaddingLeft(10); cell2.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell(new Paragraph( String.valueOf(service.getTotalCellCasesBySyllabus( service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()))), content)); cell3.setBorder(0); cell3.setPaddingLeft(10); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell4 = new PdfPCell(new Paragraph( String.valueOf(service.getTotalCellItemsByCellCaseId( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())))), content)); cell4.setBorder(0); cell4.setPaddingLeft(10); cell4.setHorizontalAlignment(Element.ALIGN_CENTER); cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); table2.addCell(cell1); table2.addCell(cell2); table2.addCell(cell3); table2.addCell(cell4); document.add(table2); } } } } catch (DocumentException ex) { Logger.getLogger(InventoryItemsReportPDF.class.getName()).log(Level.SEVERE, null, ex); } finally { document.close(); } }
From source file:com.etest.pdfgenerator.InventoryItemsReportPDF.java
public InventoryItemsReportPDF() { Document document = null;// w ww . jav a 2 s . co m Date date = new Date(); try { document = new Document(PageSize.LETTER.rotate(), 50, 50, 50, 50); PdfWriter.getInstance(document, outputStream); document.open(); Font header = FontFactory.getFont("Times-Roman", 12, Font.BOLD); Font content = FontFactory.getFont("Times-Roman", 10); Font dateFont = FontFactory.getFont("Times-Roman", 8); Image img = null; try { img = Image.getInstance("C:\\eTest-images\\SUCN_seal.png"); img.scaleToFit(60, 60); img.setAbsolutePosition(650, 500); } catch (BadElementException | IOException ex) { Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex); } document.add(img); Paragraph title1 = new Paragraph(); title1.setAlignment(Element.ALIGN_CENTER); title1.add(new Phrase("Inventory of Items Report")); document.add(title1); Paragraph title2 = new Paragraph(); title2.setAlignment(Element.ALIGN_CENTER); title2.add(new Phrase("Grouped According to the Revised Bloom's Taxonomy")); document.add(title2); Paragraph datePrinted = new Paragraph(); datePrinted.setSpacingAfter(20f); datePrinted.setAlignment(Element.ALIGN_CENTER); datePrinted .add(new Phrase("Date printed: " + new SimpleDateFormat("dd MMMM yyyy").format(date), content)); document.add(datePrinted); PdfPTable table = new PdfPTable(8); table.setWidthPercentage(100); table.setSpacingAfter(5f); for (int i = 0; i < tableHeader.length; i++) { PdfPCell cell = new PdfPCell(new Phrase(tableHeader[i], header)); cell.setBorder(Rectangle.NO_BORDER); cell.setPaddingLeft(10); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); if (tableHeader[i].equals("Subject")) { cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); } else { cell.setHorizontalAlignment(Element.ALIGN_CENTER); } table.addCell(cell); } document.add(table); for (InventoryOfCasesReport report : service.getInventoryOfCases()) { PdfPTable table2 = new PdfPTable(8); table2.setWidthPercentage(100); table2.setSpacingBefore(3f); table2.setSpacingAfter(3f); if (!service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId()).isEmpty()) { if (!service .getListOfCellCaseIdBySyllabusId( service.getListOfSyllabusIdByCurriculumId(report.getCurriculumId())) .isEmpty()) { PdfPCell cell1 = new PdfPCell(new Paragraph(report.getSubject(), content)); cell1.setBorder(0); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell( new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())), tq.getBloomsClassId(BloomsClass.Remember.toString()))), content)); cell2.setBorder(0); cell2.setPaddingLeft(10); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell( new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())), tq.getBloomsClassId(BloomsClass.Understand.toString()))), content)); cell3.setBorder(0); cell3.setPaddingLeft(10); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell4 = new PdfPCell( new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())), tq.getBloomsClassId(BloomsClass.Apply.toString()))), content)); cell4.setBorder(0); cell4.setPaddingLeft(10); cell4.setHorizontalAlignment(Element.ALIGN_CENTER); cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell5 = new PdfPCell( new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())), tq.getBloomsClassId(BloomsClass.Analyze.toString()))), content)); cell5.setBorder(0); cell5.setPaddingLeft(10); cell5.setHorizontalAlignment(Element.ALIGN_CENTER); cell5.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell6 = new PdfPCell( new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())), tq.getBloomsClassId(BloomsClass.Evaluate.toString()))), content)); cell6.setBorder(0); cell6.setPaddingLeft(10); cell6.setHorizontalAlignment(Element.ALIGN_CENTER); cell6.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell7 = new PdfPCell( new Paragraph(String.valueOf(service.getTotalItemsByBloomsTaxonomy( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())), tq.getBloomsClassId(BloomsClass.Create.toString()))), content)); cell7.setBorder(0); cell7.setPaddingLeft(10); cell7.setHorizontalAlignment(Element.ALIGN_CENTER); cell7.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell8 = new PdfPCell(new Paragraph( String.valueOf(service.getTotalCellItemsByCellCaseId( service.getListOfCellCaseIdBySyllabusId(service .getListOfSyllabusIdByCurriculumId(report.getCurriculumId())))), content)); cell8.setBorder(0); cell8.setPaddingLeft(10); cell8.setHorizontalAlignment(Element.ALIGN_CENTER); cell8.setVerticalAlignment(Element.ALIGN_MIDDLE); table2.addCell(cell1); table2.addCell(cell2); table2.addCell(cell3); table2.addCell(cell4); table2.addCell(cell5); table2.addCell(cell6); table2.addCell(cell7); table2.addCell(cell8); document.add(table2); } } } } catch (DocumentException ex) { Logger.getLogger(InventoryItemsReportPDF.class.getName()).log(Level.SEVERE, null, ex); } finally { document.close(); } }
From source file:com.etest.pdfgenerator.ItemAnalysisReportPDF.java
public ItemAnalysisReportPDF(int tqCoverageId) { this.tqCoverageId = tqCoverageId; Document document = null;//from w ww .j av a 2 s.c o m Date date = new Date(); try { document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter.getInstance(document, outputStream); document.open(); Font header = FontFactory.getFont("Times-Roman", 12, Font.BOLD); Font content = FontFactory.getFont("Times-Roman", 10); Font dateFont = FontFactory.getFont("Times-Roman", 8); Image img = null; try { img = Image.getInstance("C:\\eTest-images\\SUCN_seal.png"); img.scaleToFit(60, 60); img.setAbsolutePosition(450, 730); } catch (BadElementException | IOException ex) { Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex); } document.add(img); Paragraph reportTitle = new Paragraph(); reportTitle.setAlignment(Element.ALIGN_CENTER); reportTitle.add(new Phrase("Item Analysis Report", header)); document.add(reportTitle); Paragraph datePrinted = new Paragraph(); datePrinted.setSpacingAfter(20f); datePrinted.setAlignment(Element.ALIGN_CENTER); datePrinted.add( new Phrase("Date printed: " + new SimpleDateFormat("dd MMMM yyyy").format(date), dateFont)); document.add(datePrinted); Paragraph subject = new Paragraph(); subject.setAlignment(Element.ALIGN_LEFT); subject.add(new Phrase( "Subject: " + cs.getCurriculumById(tq.getTQCoverageById(getTqCoverageId()).getCurriculumId()) .getSubject().toUpperCase(), content)); document.add(subject); Paragraph term = new Paragraph(); term.setAlignment(Element.ALIGN_LEFT); term.add(new Phrase("SY and Semester Administered: 2015-16 2nd Semester", content)); document.add(term); Paragraph type = new Paragraph(); type.setSpacingAfter(20f); type.setAlignment(Element.ALIGN_LEFT); type.add( new Phrase("Type of Test: " + tq.getTQCoverageById(getTqCoverageId()).getExamTitle(), content)); document.add(type); PdfPTable table = new PdfPTable(5); table.setWidthPercentage(100); table.setWidths(new int[] { 130, 300, 300, 300, 300 }); // table.setSpacingAfter(5f); PdfPCell cellOne = new PdfPCell(new Phrase("Item No.")); cellOne.setBorderWidthTop(1); cellOne.setBorderWidthLeft(1); cellOne.setBorderWidthRight(1); cellOne.setBorderWidthBottom(1); cellOne.setPaddingLeft(10); cellOne.setPaddingRight(10); cellOne.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cellOne.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellTwo = new PdfPCell(new Phrase("Difficulty")); cellTwo.setBorderWidthTop(1); cellTwo.setBorderWidthLeft(1); cellTwo.setBorderWidthRight(1); cellTwo.setBorderWidthBottom(1); cellTwo.setHorizontalAlignment(Element.ALIGN_CENTER); cellTwo.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellThree = new PdfPCell(new Phrase("Interpretation")); cellThree.setBorderWidthTop(1); cellThree.setBorderWidthLeft(1); cellThree.setBorderWidthRight(1); cellThree.setBorderWidthBottom(1); cellThree.setHorizontalAlignment(Element.ALIGN_CENTER); cellThree.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellFour = new PdfPCell(new Phrase("Discrimination")); cellFour.setBorderWidthTop(1); cellFour.setBorderWidthLeft(1); cellFour.setBorderWidthRight(1); cellFour.setBorderWidthBottom(1); cellFour.setHorizontalAlignment(Element.ALIGN_CENTER); cellFour.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cellFive = new PdfPCell(new Phrase("Interpretation")); cellFive.setBorderWidthTop(1); cellFive.setBorderWidthLeft(1); cellFive.setBorderWidthRight(1); cellFive.setBorderWidthBottom(1); cellFive.setHorizontalAlignment(Element.ALIGN_CENTER); cellFive.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cellOne); table.addCell(cellTwo); table.addCell(cellThree); table.addCell(cellFour); table.addCell(cellFive); table.getDefaultCell().setBorderWidth(0f); document.add(table); PdfPTable table2 = new PdfPTable(5); table2.setWidthPercentage(100); table2.setWidths(new int[] { 130, 300, 300, 300, 300 }); int itemNo = 1; for (CellItem ci : cis.getItemAnalysisResult(tqCoverageId)) { PdfPCell cell1 = new PdfPCell(new Paragraph(String.valueOf(itemNo), content)); cell1.setBorderWidthTop(1); cell1.setBorderWidthLeft(1); cell1.setBorderWidthRight(1); cell1.setBorderWidthBottom(1); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell(new Paragraph(String.valueOf(ci.getDifficultIndex()), content)); cell2.setBorderWidthTop(1); cell2.setBorderWidthLeft(1); cell2.setBorderWidthRight(1); cell2.setBorderWidthBottom(1); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell(new Paragraph( ItemAnalysisInterpretation.getDifficultyInterpretation(ci.getDifficultIndex()), content)); cell3.setBorderWidthTop(1); cell3.setBorderWidthLeft(1); cell3.setBorderWidthRight(1); cell3.setBorderWidthBottom(1); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell4 = new PdfPCell(new Paragraph(String.valueOf(ci.getDiscriminationIndex()), content)); cell4.setBorderWidthTop(1); cell4.setBorderWidthLeft(1); cell4.setBorderWidthRight(1); cell4.setBorderWidthBottom(1); cell4.setHorizontalAlignment(Element.ALIGN_CENTER); cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell5 = new PdfPCell(new Paragraph( ItemAnalysisInterpretation.getDiscriminationInterpretation(ci.getDiscriminationIndex()), content)); cell5.setBorderWidthTop(1); cell5.setBorderWidthLeft(1); cell5.setBorderWidthRight(1); cell5.setBorderWidthBottom(1); cell5.setHorizontalAlignment(Element.ALIGN_CENTER); cell5.setVerticalAlignment(Element.ALIGN_MIDDLE); table2.addCell(cell1); table2.addCell(cell2); table2.addCell(cell3); table2.addCell(cell4); table2.addCell(cell5); itemNo++; } table.getDefaultCell().setBorderWidth(0f); document.add(table2); } catch (DocumentException ex) { Logger.getLogger(ItemAnalysisReportPDF.class.getName()).log(Level.SEVERE, null, ex); } finally { document.close(); } }
From source file:com.etest.pdfgenerator.TQCoveragePDF.java
public TQCoveragePDF(int tqCoverageId) { this.tqCoverageId = tqCoverageId; Document document = null;//from w w w . jav a 2 s.c o m try { document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter.getInstance(document, outputStream); document.open(); Font header1 = FontFactory.getFont("Times-Roman", 14, Font.BOLD); Font header2 = FontFactory.getFont("Times-Roman", 12, Font.BOLD); Font content = FontFactory.getFont("Times-Roman", 10); Image img = null; try { img = Image.getInstance("C:\\eTest-images\\SUCN_seal.png"); img.scaleToFit(60, 60); img.setAbsolutePosition(100, 720); } catch (BadElementException | IOException ex) { Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex); } document.add(img); Paragraph title = new Paragraph(); title.setAlignment(Element.ALIGN_CENTER); title.add(new Phrase("COLLEGE OF NURSING", header2)); document.add(title); Paragraph school = new Paragraph(); school.setAlignment(Element.ALIGN_CENTER); school.add(new Phrase("Siliman University", header2)); document.add(school); Paragraph location = new Paragraph(); location.setSpacingAfter(10f); location.setAlignment(Element.ALIGN_CENTER); location.add(new Phrase("Dumaguete City", header2)); document.add(location); Paragraph examTitle = new Paragraph(); examTitle.setSpacingAfter(20f); examTitle.setAlignment(Element.ALIGN_CENTER); examTitle .add(new Phrase( cs.getCurriculumById(tq.getTQCoverageById(getTQCoverageId()).getCurriculumId()) .getSubject() + " " + tq.getTQCoverageById(getTQCoverageId()).getExamTitle(), header2)); document.add(examTitle); Paragraph instruction = new Paragraph(); instruction.setSpacingAfter(5f); instruction.setAlignment(Element.ALIGN_LEFT); instruction.add( new Phrase("INSTRUCTIONS: Read the cases carefully. Choose the letter of the correct answer. " + "Use an answer sheet and follow instruction for its use.", content)); document.add(instruction); int itemNo = 1; Map<Integer, Map<Integer, Integer>> tqCoverage = tq.getTQCoverage(getTQCoverageId()); for (Map.Entry<Integer, Map<Integer, Integer>> tqCases : tqCoverage.entrySet()) { Integer tqCaseId = tqCases.getKey(); Label caseTopic = new Label(); caseTopic.setValue(ccs.getCellCaseById(tqCaseId).getCaseTopic()); caseTopic.setContentMode(ContentMode.HTML); document.add(new Paragraph(caseTopic.getValue().replaceAll("(?i)<p.*?>.*?</p>", ""), content)); Map<Integer, Integer> value = tqCases.getValue(); for (Map.Entry<Integer, Integer> itemIds : value.entrySet()) { Integer itemId = itemIds.getKey(); Integer itemKeyId = itemIds.getValue(); List<String> keyList = k.getAllItemKey(itemId); if (keyList.isEmpty()) { ShowErrorNotification.error( "No Item Key was found for STEM: \n" + cis.getCellItemById(itemId).getItem()); return; } Label stem = new Label(); // stem.setValue(itemNo+". "+cis.getCellItemById(itemId).getItem().replace("{key}", keyList.get(0))); stem.setValue(itemNo + ". " + cis.getCellItemById(itemId).getItem().replace("{key}", k.getItemKeyById(itemKeyId))); stem.setContentMode(ContentMode.HTML); document.add(new Paragraph(stem.getValue(), content)); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); table.setSpacingBefore(10f); table.setSpacingAfter(10f); //Set Column widths float[] columnWidths = { 1f, 1f }; table.setWidths(columnWidths); PdfPCell cell1 = new PdfPCell( new Paragraph("A) " + cis.getCellItemById(itemId).getOptionA(), content)); // cell1.setBorderColor(BaseColor.BLUE); cell1.setBorder(0); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell( new Paragraph("C) " + cis.getCellItemById(itemId).getOptionC(), content)); // cell2.setBorderColor(BaseColor.GREEN); cell2.setBorder(0); cell2.setPaddingLeft(10); cell2.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell( new Paragraph("B) " + cis.getCellItemById(itemId).getOptionB(), content)); // cell3.setBorderColor(BaseColor.RED); cell3.setBorder(0); cell3.setPaddingLeft(10); cell3.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell4 = new PdfPCell( new Paragraph("D) " + cis.getCellItemById(itemId).getOptionD(), content)); // cell4.setBorderColor(BaseColor.RED); cell4.setBorder(0); cell4.setPaddingLeft(10); cell4.setHorizontalAlignment(Element.ALIGN_JUSTIFIED); cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); table.addCell(cell4); document.add(table); itemNo++; } } document.newPage(); Paragraph ticketNo = new Paragraph(); ticketNo.setSpacingAfter(30f); ticketNo.setAlignment(Element.ALIGN_LEFT); ticketNo.add(new Phrase("TQ Ticket #: " + tq.getTqCoverageTicketNo(getTQCoverageId()), content)); document.add(ticketNo); document.add(new Paragraph("Answer Key: ")); itemNo = 1; List<TQAnswerKey> answerKey = tq.getTQCoverageAnswerKey(getTQCoverageId()); for (TQAnswerKey t : answerKey) { document.add(new Paragraph( t.getItemNo() + ": " + cis.getOptionAnswer(t.getCellItemId()).get(t.getAnswer()))); } } catch (DocumentException ex) { Logger.getLogger(TQCoveragePDF.class.getName()).log(Level.SEVERE, null, ex); } finally { if (document != null) { document.close(); } } }
From source file:com.example.admin.avoidq.billGenerated.java
private void generatePDF(final String personName) { new Thread(new Runnable() { public void run() { // a potentially time consuming task //create a new document Document document = new Document(); try { PdfWriter docWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile)); document.open();/*w w w. ja va 2 s. c om*/ PdfContentByte cb = docWriter.getDirectContent(); //initialize fonts for text printing initializeFonts(); //the company logo is stored in the assets which is read only //get the logo and print on the document /* try { bitmap11 = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300); iv.setImageBitmap(bitmap11); } catch (WriterException e) { e.printStackTrace(); } * */ InputStream inputStream = getAssets().open("sale.png"); Bitmap bmp = null;//BitmapFactory.decodeStream(inputStream); bmp = bitmap11; ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); Image companyLogo = Image.getInstance(stream.toByteArray()); companyLogo.setAbsolutePosition(25, 700); companyLogo.scalePercent(65); document.add(companyLogo); Calendar calendar = Calendar.getInstance(); SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy"); String formattedDate = df1.format(calendar.getTime()); //creating a sample invoice with some customer data createHeadings(cb, 400, 780, "Date :"); createHeadings(cb, 430, 780, formattedDate); String fname = customer.getName(); String lname = customer.getSurname(); createHeadings(cb, 400, 765, "Customer :"); createHeadings(cb, 445, 765, fname + " " + lname); String mob = customer.getMobile_no(); createHeadings(cb, 400, 750, "Mobile No :"); createHeadings(cb, 445, 750, mob); createHeadings(cb, 400, 735, "Shop :"); createHeadings(cb, 430, 735, "Empress Mall"); createHeadings(cb, 400, 720, "City :"); createHeadings(cb, 430, 720, "Nagpur"); // createHeadings(cb,400,720,"Country"); //list all the products sold to the customer float[] columnWidths = { 1.5f, 3f, 2.5f, 2.5f, 2f, 2f }; //create PDF table with the given widths PdfPTable table = new PdfPTable(columnWidths); // set table width a percentage of the page width table.setTotalWidth(500f); PdfPCell cell = new PdfPCell(new Phrase("S.NO")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Item Name")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Price")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Quantity")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Discount")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Amount")); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); table.setHeaderRows(1); /*DecimalFormat df = new DecimalFormat("0.000"); for(int i=0; i < 10; i++ ){ double price = Double.valueOf(df.format(Math.random() * 10)); double extPrice = price * (i+1) ; table.addCell(String.valueOf(i+1)); table.addCell("ITEM" + String.valueOf(i+1)); table.addCell(String.valueOf(5*i)); table.addCell(String.valueOf(1)); table.addCell(String.valueOf(i)+ " %"); table.addCell(df.format(extPrice)); }*/ int sr = 0; DecimalFormat df = new DecimalFormat("0.0"); double total_price = 0; //Log.i("c0","c0 = "+carts[0].getItemname()+" "+String.valueOf(carts[0].getPrice())); // Log.i("c1","c1 = "+carts[1].getItemname()+" "+String.valueOf(carts[1].getPrice())); for (Cart cd : carts) { Log.i("cartscheck", "carts check = " + cd.getBarcode() + " " + cd.getItemname() + " " + String.valueOf(cd.getPrice())); } for (Cart c : carts) { double price = c.getPrice(); int quantity = c.getQuantity(); price = (price / quantity); double discont = c.getDiscount(); sr++; table.addCell(String.valueOf(sr)); table.addCell(c.getItemname()); table.addCell(df.format(price)); table.addCell(String.valueOf(quantity)); table.addCell(df.format(discont) + " %"); double total = (price * quantity); total_price = total_price + total; Log.i("total", "total in for loop = " + String.valueOf(total)); table.addCell(df.format(total)); } float headerHeight = table.getHeaderHeight(); Log.i("headerHeight", String.valueOf(headerHeight)); //absolute location to print the PDF table from table.writeSelectedRows(0, -1, document.leftMargin(), 650, docWriter.getDirectContent()); float total_height = table.getTotalHeight(); Log.i("total_height", String.valueOf(total_height)); createHeadings(cb, 420, 750f - 125f - total_height, "Total Price = "); createHeadings(cb, 475, 750f - 125f - total_height, String.valueOf(total_price)); //print the signature image along with the persons name inputStream = getAssets().open("user.png"); bmp = BitmapFactory.decodeStream(inputStream); stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); Image signature = Image.getInstance(stream.toByteArray()); signature.setAbsolutePosition(400f, 750f - 125f - total_height - 60f); signature.scalePercent(35f); document.add(signature); createHeadings(cb, 450, 750f - 125f - total_height - 80f, fname + " " + lname); document.close(); } catch (Exception e) { e.printStackTrace(); } //PDF file is now ready to be sent to the bluetooth printer using PrintShare Intent i = new Intent(Intent.ACTION_VIEW); // i.setPackage("com.dynamixsoftware.printershare"); i.setDataAndType(Uri.fromFile(pdfFile), "application/pdf"); startActivity(i); } }).start(); }