@Override public PdfPTable generatePage() throws Exception { Image image = Image.getInstance(imageFile.toURL()); float heightToWidthRatio = (210f / 297f); Image imageCropped = ImageUtils.cropImageToMeetRatio(pdfWriter, image, heightToWidthRatio); PdfPCell cell = new PdfPCell(imageCropped, true); cell.setBorder(0); cell.setPadding(COVER_MARGIN); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setExtraParagraphSpace(0); cell.setRightIndent(0); PdfPTable table = new PdfPTable(1); ; table.setWidthPercentage(100f); table.setWidths(new int[]{1}); table.setExtendLastRow(true); table.addCell(cell); return table; }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // TODO: force iText to respect the order in which content is added writer.setStrictImageSequence(true); document.open(); // step 4 - add content into document String[] imageNames = { "35_Cal_Crutchlow.jpg", "38_Bradley_Smith.jpg", "46_Valentino_Rossi.jpg", "99_Jorge_Lorenzo.jpg" }; for (int i = 0; i < 4; i++) { Image image = Image.getInstance("resources/img/" + imageNames[i]); // TODO: scale image image.scaleToFit(500, 500); // scale size document.add(image); document.add(new Paragraph(imageNames[i])); } document.close(); }
private static PdfPCell getPhotoCell(BufferedImage bufferedImage, float scalePercent, boolean isHorizontallyCentered) throws BadElementException, IOException { Image jpeg = Image.getInstance(bufferedImage, null); jpeg.scalePercent(scalePercent); jpeg.setAlignment(Image.MIDDLE); PdfPCell photoCell = new PdfPCell(jpeg); photoCell.setBorder(0); if (isHorizontallyCentered) { photoCell.setHorizontalAlignment(Element.ALIGN_CENTER); } else { photoCell.setHorizontalAlignment(Element.ALIGN_RIGHT); } photoCell.setVerticalAlignment(Element.ALIGN_TOP); int height = (int) Math.ceil(bufferedImage.getHeight() * scalePercent / 100); photoCell.setFixedHeight(height); return photoCell; }
/** * adds an image to the document. * * @param doc * @param iji * @return * @throws InterruptedException * @throws ExecutionException * @throws IOException * @throws DocumentException */ public Document addImage(Document doc, ImageJobDescription iji) throws InterruptedException, ExecutionException, IOException, DocumentException { // create image worker ImageWorker job = new ImageWorker(dlConfig, iji); // submit Future<DocuImage> jobTicket = imageJobCenter.submit(job); // wait for result DocuImage img = jobTicket.get(); // scale the image Image pdfimg = Image.getInstance(img.getAwtImage(), null); float docW = PageSize.A4.getWidth() - 2 * PageSize.A4.getBorder(); float docH = PageSize.A4.getHeight() - 2 * PageSize.A4.getBorder(); // fit the image to the page pdfimg.scaleToFit(docW, docH); // add to PDF doc.add(pdfimg); return doc; }
public ImageInstance getImageByFile( PdfContentByte cb , File file ) throws IOException, BadElementException{ Image image = null; ImageInstance instance = null; if( file.getName().toLowerCase().endsWith( ".pdf")){ PdfReader reader = new PdfReader( file.getAbsolutePath() ); PdfImportedPage p = cb.getPdfWriter().getImportedPage(reader, 1); image = Image.getInstance(p); instance = new ImageInstance(image, reader); }else{ image = Image.getInstance( file.getAbsolutePath() ); instance = new ImageInstance(image, null); } instances.add(instance); return instance; }
public static void main(String[] args) { Image img = getImageFromUrl("http://oimagea6.ydstatic.com/image?url=http://en.wikipedia.org/wiki/File:WhiteCat.jpg&product=PICDICT_EDIT"); System.out.println("img.width=" + img.getWidth() + " img.hight=" + img.getHeight()); System.out.println( getAutoZoomHeightByWidth("http://oimagea6.ydstatic.com/image?url=http://en.wikipedia.org/wiki/File:WhiteCat.jpg&product=PICDICT_EDIT", 120)); System.out.println( getAutoZoomHeightByWidth("http://oimagea6.ydstatic.com/image?url=http://en.wikipedia.org/wiki/File:WhiteCat.jpg&product=PICDICT_EDIT", 200)); System.out.println( getAutoZoomWidthByHeight("http://oimagea6.ydstatic.com/image?url=http://en.wikipedia.org/wiki/File:WhiteCat.jpg&product=PICDICT_EDIT", 80)); System.out.println( getAutoZoonImageHtmlByWidth("http://oimagea6.ydstatic.com/image?url=http://en.wikipedia.org/wiki/File:WhiteCat.jpg&product=PICDICT_EDIT", 120)); System.out.println(getAutoZoonImageHtmlByWidth( "http://oimageb1.ydstatic.com/image?url=http://mydrupalsite.co.uk/JJLJ/sites/default/files/images/computer_pig_logo-cartoon-pig.jpg&product=PICDICT_EDIT", 120)); }
public Document getPDF() throws Exception { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(FILE + problem.getPid() + ".pdf")); Image image = Image.getInstance(this.logo); document.open(); document.add(image); document.addCreationDate(); document.add(new Paragraph("Title: "+problem.getTitle())); document.add(new Paragraph("Code: "+problem.getPid())); document.add(new Paragraph(" ")); document.add(addParagraph("Description",problem.getDescription(), true)); document.add(addParagraph("Input",problem.getInput(), true)); document.add(addParagraph("Output",problem.getOutput(), true)); document.add(addParagraph("Input Example",problem.getInputex().replaceAll("<br/>", ""), true)); document.add(addParagraph("Output Example",problem.getOutputex(), true)); document.add(new Paragraph("Time(ms): "+problem.getTime())); document.add(new Paragraph("Memory(kb): "+problem.getMemory())); document.add(new Paragraph("Source(kb): "+problem.getFontsize())); document.addTitle("Challenger Online Judge"); document.addAuthor("Chjudge"); document.close(); return document; }
private void putSignature(PdfPTable table, Context context) throws Exception { String uploadOid = (String)context.get("uploadSignatureOid"); if ( StringUtils.isBlank(uploadOid) ) { return; } byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid ); if ( null == imageBytes ) { return; } Image signatureImgObj = Image.getInstance( imageBytes ); signatureImgObj.setWidthPercentage(40f); PdfPCell cell = new PdfPCell(); cell.setBorder( Rectangle.NO_BORDER ); cell.addElement(signatureImgObj); table.addCell(cell); }
private float reshapeImage(Image image, float imagewidthmax, float imageheightmax){ float imageheight = image.getHeight(); float imagewidth = image.getWidth(); float scaler; if((imageheightmax>imageheight)&&(imageheightmax>imagewidth)) return 1; if(imageheight < imagewidth){ scaler = imagewidthmax/image.getWidth()*100; image.scalePercent(scaler); } else { scaler = imageheightmax/image.getHeight()*100; image.scalePercent(scaler); } return scaler/100; }
@Override public void buildComponent(SerialisationContext pSerialisationContext, PDFSerialiser pSerialiser, EvaluatedHtmlPresentationNode pEvalNode) { Map<String, StringAttributeResult> lNodeAttributes = pEvalNode.getAttributeMap(false); String lSourceURI = Optional.ofNullable(lNodeAttributes.get(IMAGE_SOURCE_ATTRIBUTE)) .map(StringAttributeResult::getString) .flatMap(Optional::ofNullable) .orElseThrow(() -> new ExInternal("Could not find '" + IMAGE_SOURCE_ATTRIBUTE + "' attribute on HTML image")); Image lImage = getImage(pSerialisationContext, lSourceURI); // Set the image dimensions if specified in the node attributes, using the current element attributes if dimensions // are specified in relative units e.g. ems setImageDimensions(lImage, lNodeAttributes, pSerialiser.getElementAttributes()); // Add the image within a chunk so it appears inline and changes the line leading to fit the image pSerialiser.add(new Chunk(lImage, IMAGE_X_OFFSET, IMAGE_Y_OFFSET, true)); }
void addRotatedImage(PdfContentByte contentByte, Image image, float x, float y, float width, float height, float rotation) throws DocumentException { // Draw image at x,y without rotation contentByte.addImage(image, width, 0, 0, height, x, y); // Draw image as if the previous image was rotated around its center // Image starts out being 1x1 with origin in lower left // Move origin to center of image AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5); // Stretch it to its dimensions AffineTransform B = AffineTransform.getScaleInstance(width, height); // Rotate it AffineTransform C = AffineTransform.getRotateInstance(rotation); // Move it to have the same center as above AffineTransform D = AffineTransform.getTranslateInstance(x + width/2, y + height/2); // Concatenate AffineTransform M = (AffineTransform) A.clone(); M.preConcatenate(B); M.preConcatenate(C); M.preConcatenate(D); //Draw contentByte.addImage(image, M); }
static byte[] createSimpleImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 500, 500); g2d.dispose(); Image image = Image.getInstance(bim, null); document.add(image); document.close(); return baos.toByteArray(); }
static byte[] createRotatedImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte directContent = writer.getDirectContent(); BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 500, 500); g2d.dispose(); Image image = Image.getInstance(bim, null); directContent.addImage(image, 0, 500, -500, 0, 550, 50); document.close(); return baos.toByteArray(); }
static byte[] createMultiUseImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); BufferedImage bim = new BufferedImage(500, 250, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 250, 250); g2d.dispose(); Image image = Image.getInstance(bim, null); document.add(image); document.add(image); document.add(image); document.close(); return baos.toByteArray(); }
public static byte[] stampLayer(InputStream _pdfFile, Image iImage, int x, int y, String layername, boolean readLayers) throws IOException, DocumentException { PdfReader reader = new PdfReader(_pdfFile); try ( ByteArrayOutputStream ms = new ByteArrayOutputStream() ) { PdfStamper stamper = new PdfStamper(reader, ms); //Don't delete otherwise the stamper flattens the layers if (readLayers) stamper.getPdfLayers(); PdfLayer logoLayer = new PdfLayer(layername, stamper.getWriter()); PdfContentByte cb = stamper.getUnderContent(1); cb.beginLayer(logoLayer); //300dpi iImage.scalePercent(24f); iImage.setAbsolutePosition(x, y); cb.addImage(iImage); cb.endLayer(); stamper.close(); return (ms.toByteArray()); } }
/** * Create a series bar code for this series * * @return Image */ private Image getBarCode() { UUID uuid = UUID.fromString(s.getSeries().getIdentifier().getValue()); LabBarcode barcode = new LabBarcode(LabBarcode.Type.SERIES, uuid); //barcode.setX(0.4f); //barcode.setSize(1f); //barcode.setBarHeight(10f); barcode.setBaseline(-1f); //barcode.setFont(null); Image image = barcode.createImageWithBarcode(cb, null, null); image.setWidthPercentage(95); return image; }
/** * Create a series bar code for this series * * @return Image */ private Image getBarCode(WSIBox b) { UUID uuid = UUID.fromString(b.getIdentifier().getValue()); LabBarcode barcode = new LabBarcode(LabBarcode.Type.BOX, uuid); //barcode.setX(1f); //barcode.setN(0.5f); barcode.setSize(5f); barcode.setBaseline(-1f); barcode.setBarHeight(60f); Image image = barcode.createImageWithBarcode(cb, null, null); return image; }
/** * Create a series bar code for this series * * @return Image */ private Image getBarCode(WSIBox b) { UUID uuid = UUID.fromString(b.getIdentifier().getValue()); LabBarcode barcode = new LabBarcode(LabBarcode.Type.BOX, uuid); barcode.setX(0.7f); //barcode.setN(0.5f); barcode.setSize(6f); barcode.setBaseline(8f); barcode.setBarHeight(50f); Image image = barcode.createImageWithBarcode(cb, null, null); return image; }
/** * Create a series bar code for this series * * @return Image */ private static Image getBarCode(PdfContentByte cb, TridasSample s) { UUID uuid = UUID.fromString(s.getIdentifier().getValue()); LabBarcode barcode = new LabBarcode(LabBarcode.Type.SAMPLE, uuid); barcode.setX(1.0f); //barcode.setN(0.5f); //barcode.setSize(6f); barcode.setFont(null); //barcode.setBaseline(8f); barcode.setBarHeight(20f); Image image = barcode.createImageWithBarcode(cb, null, null); return image; }
public void IMGToPDF(String RESOURCES, String result) throws DocumentException, FileNotFoundException, BadElementException, IOException{ ProgressBar progrsbar=new ProgressBar(); progrsbar.showProgress(); Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result)); // step 3 document.open(); // step 4 Image img; img = Image.getInstance(RESOURCES); Image.getInstance(img); document.add(img); progrsbar.updatePercent(100); document.close(); }
public static void addImage(byte[] input, OutputStream output, Image image, String placeholder) throws IOException, DocumentException { try (PdfReaderAutoclosable pdfReader = new PdfReaderAutoclosable(input); PdfStamperAutoclosable pdfStamper = new PdfStamperAutoclosable(pdfReader, output)) { AcroFields form = pdfStamper.getAcroFields(); List<AcroFields.FieldPosition> positions = form.getFieldPositions(placeholder); positions.forEach(p -> { image.scaleToFit(p.position.getWidth(), p.position.getHeight()); image.setAbsolutePosition(p.position.getLeft() + (p.position.getWidth() - image.getScaledWidth()) / 2, p.position.getBottom() + (p.position.getHeight() - image.getScaledHeight()) / 2); PdfContentByte cb = pdfStamper.getOverContent(p.page); try { cb.addImage(image); } catch(DocumentException e) { throw Throwables.propagate(e); } }); } }
public void addStructureTreeToDocument(String inputFile, String outputFile, TEIDocument teiDocument) throws IOException, DocumentException { PdfReader reader = new PdfReader(inputFile); Document document = new Document(reader.getPageSize(1), 0f, 0f, 0f, 0f); document.setRole(PdfName.ARTIFACT); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); writer.setTagged(); writer.setUserProperties(true); document.open(); int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { PdfImportedPage importedPage = writer.getImportedPage(reader, i); importedPage.setRole(PdfName.ARTIFACT); Image image = Image.getInstance(importedPage); image.setRole(PdfName.ARTIFACT); document.add(image); } final PdfStructureTreeRoot root = writer.getStructureTreeRoot(); List<TEIElement> teiElementList = teiDocument.getBody(); for (TEIElement teiElement : teiElementList) { teiElement.toPdfStructureElement(root); } document.close(); reader.close(); writer.close(); }
private PdfPTable createBarcodeTable(PdfContentByte cb, String caption, String detail, String code) { // Barcode Generation Barcode39 codeEAN = new Barcode39(); codeEAN.setCode(code); Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null); // Table PdfPTable table = new PdfPTable(1); table.setSpacingBefore(10); table.setSpacingAfter(10); table.setTotalWidth(80); table.setLockedWidth(true); PdfPCell cell1 = new PdfPCell(imageEAN); PdfPCell cell2 = new PdfPCell(new Paragraph(caption)); PdfPCell cell3 = new PdfPCell(new Paragraph(detail)); cell1.setBorder(Rectangle.NO_BORDER); cell2.setBorder(Rectangle.NO_BORDER); cell3.setBorder(Rectangle.NO_BORDER); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); return table; }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); PdfPTable table = new PdfPTable(2); PdfReader reader = new PdfReader(T08_Chapter.RESULT); int n = reader.getNumberOfPages(); for (int pageNumber = 1; pageNumber <= n; pageNumber++) { // TODO: import page as image PdfImportedPage page = writer.getImportedPage(reader, pageNumber); table.addCell(Image.getInstance(page)); } document.add(table); document.close(); }
@Override public void onEndPage(PdfWriter writer, Document document) { try { footer = buildPdfTable(PRINT_PAGE_FOOTER); if (footer != null) { printPageFooterBand(); Rectangle page = document.getPageSize(); footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); footer.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent()); String image = bean.getReportLayout().getBackgroundImage(); if (image != null) { byte[] imageBytes = getImage(image); Image pdfImage = Image.getInstance(imageBytes); pdfImage.setAbsolutePosition(0, 0); writer.getDirectContentUnder().addImage(pdfImage); } } } catch (Exception e) { throw new ExceptionConverter(e); } finally { pageNo = writer.getPageNumber(); } }
public String savePageAsPdf(boolean scaled) throws IOException, DocumentException { String pdfName = ""; // Define test screenshot root String test = ""; if (TestNamingUtil.isTestNameRegistered()) { test = TestNamingUtil.getTestNameByThread(); } else { test = "undefined"; } File testRootDir = ReportContext.getTestDir(); File artifactsFolder = ReportContext.getArtifactsFolder(); String fileID = test.replaceAll("\\W+", "_") + "-" + System.currentTimeMillis(); pdfName = fileID + ".pdf"; String fullPdfPath = artifactsFolder.getAbsolutePath() + "/" + pdfName; // TODO: test this implementation and change back to capture if necessary Image image = Image.getInstance(testRootDir.getAbsolutePath() + "/" + Screenshot.captureFailure(driver, "")); Document document = null; if (scaled) { document = new Document(PageSize.A4, 10, 10, 10, 10); if (image.getHeight() > (document.getPageSize().getHeight() - 20) || image.getScaledWidth() > (document.getPageSize().getWidth() - 20)) { image.scaleToFit(document.getPageSize().getWidth() - 20, document.getPageSize().getHeight() - 20); } } else { document = new Document(new RectangleReadOnly(image.getScaledWidth(), image.getScaledHeight())); } PdfWriter.getInstance(document, new FileOutputStream(fullPdfPath)); document.open(); document.add(image); document.close(); return fullPdfPath; }
/** * 將排序過的圖片轉成PDF * * @param pageSize * pdf的文件大小:A4 or B3 etc... * @param sourceFolderPath * 圖片所在的資料夾路徑 * @param pathList * 排序過的圖片列表 * @param targetPdfPath * 要儲存的的PDF路徑 * @return * @throws Exception */ public static boolean comicFolderToPDF(Rectangle pageSize, String sourceFolderPath, ArrayList<String> pathList, String targetPdfPath) throws Exception { boolean result = false; Document document = new Document(pageSize); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(targetPdfPath)); writer.setPageEvent(new HeaderFooter(14)); document.open(); for (String filename : pathList) { String filePath = sourceFolderPath + File.separator + filename; document.newPage(); Image img = Image.getInstance(filePath); img.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight()); img.setBorderColor(BaseColor.WHITE); document.add(img); } result = true; document.close(); return result; }
/** * Update NDA file with visitor name and visitor signature. * * @param destFile * @param signatureImage signature file * @param visitorName * @return File */ public static File build(Path destFile, File signatureImage, String visitorName) { try { PdfReader pdfReader = new PdfReader(ndaUrl); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(destFile.toString())); Image image = createNDAImage(signatureImage, 0, 0); PdfContentByte over = pdfStamper.getOverContent(5); over.addImage(image); PdfContentByte pdfContentByte = pdfStamper.getOverContent(5); pdfContentByte.beginText(); pdfContentByte.setFontAndSize(BaseFont.createFont (BaseFont.HELVETICA, BaseFont.CP1257, BaseFont.EMBEDDED ) , 10); pdfContentByte.setTextMatrix(112, 428); pdfContentByte.showText(visitorName); pdfContentByte.setTextMatrix(89, 406); pdfContentByte.showText(new SimpleDateFormat("E, dd MMM yyyy").format(new Date())); pdfContentByte.endText(); pdfStamper.close(); return destFile.toFile(); } catch (IOException | DocumentException | NumberFormatException e) { logger.error("Exception while generating NDA file. ",e); return null; } }
/** * Create itextPdf image object with visitor signature. * * @param file * @param imgHeight * @param imgWidth * @return com.itextpdf.text.Image */ public static Image createNDAImage(File file, int imgHeight, int imgWidth) { try { Image image = Image.getInstance(file.getAbsolutePath()); if (imgHeight!=0 && imgWidth!=0) { image.scaleAbsolute(imgWidth, imgHeight); } else { image.scaleAbsolute(230, 140); } image.setAbsolutePosition(70, 450); return image; } catch (BadElementException | IOException e) { logger.error("Exception while creating image for NDA file. ",e); return null; } }
private void dataTableTitile(Document documento, String data) throws IOException, BadElementException, DocumentException { try { pTableEmpresaPricipal = new PdfPTable(new float[]{15f, 85f}); pTableEmpresaInforImpres1 = new PdfPTable(1); pTableEmpresaInforImpres5 = new PdfPTable(1); PdfPCell pCellNomeEmpresa = new PdfPCell(new Phrase(Empresa.NOME, fontCabecalhoNG)); pCellNomeEmpresa.setBorder(0); PdfPCell pCellNomeEndereco = new PdfPCell(new Phrase(Empresa.ENDERECO, fontCabecalhoN)); pCellNomeEndereco.setBorder(0); PdfPCell pCellCaixaPostal = new PdfPCell(new Phrase(Empresa.CAIXAPOSTAL, fontCabecalhoN)); pCellCaixaPostal.setBorder(0); PdfPCell pCellTeleFax = new PdfPCell(new Phrase(Empresa.TELEFAX + " " + ConfigDoc.Empresa.EMAIL, fontCabecalhoN)); pCellTeleFax.setBorder(0); PdfPCell pCellSociedade = new PdfPCell(new Phrase(Empresa.SOCIEDADE, fontCabecalhoN)); pCellSociedade.setBorder(0); Image imageEmpresa = Image.getInstance("logo.png"); imageEmpresa.scaleToFit(120f, 85f); pTableEmpresaInforImpres1.addCell(pCellNomeEmpresa); pTableEmpresaInforImpres1.addCell(pCellNomeEndereco); pTableEmpresaInforImpres1.addCell(pCellCaixaPostal); pTableEmpresaInforImpres1.addCell(pCellTeleFax); pTableEmpresaInforImpres1.addCell(pCellSociedade); PdfPCell cellTabela3 = new PdfPCell(pTableEmpresaInforImpres1); cellTabela3.setBorder(0); pTableEmpresaInforImpres5.addCell(cellTabela3); PdfPCell cellTabela5 = new PdfPCell(pTableEmpresaInforImpres5); cellTabela5.setBorder(0); PdfPCell cellTabela6 = new PdfPCell(imageEmpresa); cellTabela6.setBorder(0); pTableEmpresaPricipal.setWidthPercentage(95); pTableEmpresaPricipal.addCell(cellTabela6); pTableEmpresaPricipal.addCell(cellTabela5); PdfPTable pTableTitulo = new PdfPTable(1); pTableTitulo.setHorizontalAlignment(Element.ALIGN_CENTER); pTableTitulo.setWidthPercentage(100); SimpleDateFormat sdfEsp = new SimpleDateFormat("MMMM, yyyy", Locale.ENGLISH); SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy"); PdfPCell cellTitulo = new PdfPCell(new Phrase("TOTAL PREMIUM COLLECTED ON TRAVEL INSURANCE AND TAXES FOR "+sdfEsp.format(sdf.parse(data)).toUpperCase(), fontCorpoNG)); cellTitulo.setBorder(0); cellTitulo.setPaddingBottom(10f); pTableTitulo.addCell(cellTitulo); pTableEmpresaPricipal.setHorizontalAlignment(Element.ALIGN_CENTER); documento.add(pTableEmpresaPricipal); documento.add(pTableNull); documento.add(pTableTitulo); } catch (ParseException ex) { Logger.getLogger(ExporOnlyViagemPdf.class.getName()).log(Level.SEVERE, null, ex); } }
public static void writeSimplePdf() throws Exception{ //1.新建document对象 //第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。 Document document = new Document(PageSize.A4, 50, 50, 50, 50); //2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。 //创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\Documents\\ITextTest.pdf")); //3.打开文档 document.open(); //4.向文档中添加内容 //通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落 BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font fontChinese = new Font(bfChinese, 22, Font.BOLD, BaseColor.BLACK); document.add(new Paragraph("sdfsdfsd全是中文显示了没.fsdfsfs",fontChinese)); document.add(new Paragraph("Some more text on the first page with different color and font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new BaseColor(255, 150, 200)))); Paragraph pragraph=new Paragraph("你这里有中亠好", fontChinese); document.add(pragraph); //图像支持格式 GIF, Jpeg, PNG, wmf Image gif = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png"); gif.setBorder(5); gif.scaleAbsolute(30,30); gif.setAlignment(Image.RIGHT|Image.TEXTWRAP); document.add(gif); Paragraph pragraph11=new Paragraph("你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好", fontChinese); document.add(pragraph11); Image gif15 = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png"); // gif15.setBorder(50); gif15.setBorder(Image.BOX); gif15.setBorderColor(BaseColor.RED); // gif15.setBorderColorBottom(borderColorBottom) gif15.setBorderWidth(1); gif15.scalePercent(50); document.add(gif15); //5.关闭文档 document.close(); }
/** * Adds a header to every page * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { PdfPTable table = new PdfPTable(3); try { table.setWidths(new int[]{40,5,10}); table.setTotalWidth(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); Font font=new Font(chineseFont,8); font.setColor(new BaseColor(55,55,55)); Paragraph paragraph=new Paragraph("第 "+writer.getPageNumber()+" 页 共",font); paragraph.setAlignment(Element.ALIGN_RIGHT); table.addCell(paragraph); Image img=Image.getInstance(total); img.scaleAbsolute(28, 28); PdfPCell cell = new PdfPCell(img); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); PdfPCell c = new PdfPCell(new Paragraph("页",font)); c.setHorizontalAlignment(Element.ALIGN_LEFT); c.setBorder(Rectangle.NO_BORDER); table.addCell(c); float center=(document.getPageSize().getWidth())/2-120/2; table.writeSelectedRows(0, -1,center,30, writer.getDirectContent()); } catch(DocumentException de) { throw new ExceptionConverter(de); } }
public static String getAutoZoonImageHtmlByMaxDimen(String imgUrl, int imageMaxDimen, int border) { String ret = null; Image img = getImageFromUrl(imgUrl); if (img == null) { return null; } else { float w = img.getWidth(); float h = img.getHeight(); if (w >= h) { //宽度较大,以宽度作为基准来自动缩放 ret = String.format("<p align=\"left\"><img width=\"%s\" height=\"%s\" border=\"%s\" src=\"%s\"></p>", imageMaxDimen, (int)(h * imageMaxDimen / w), border, imgUrl); } else { //高度较大 ret = String.format("<p align=\"left\"><img width=\"%s\" height=\"%s\" border=\"%s\" src=\"%s\"></p>", (int)(w * imageMaxDimen / h), imageMaxDimen, border, imgUrl); } } return ret; }
/** * 获取自动缩放后的宽度 * @author Administrator * @param url * @param height * @return */ public static int getAutoZoomWidthByHeight(String url, int height) { Image image = getImageFromUrl(url); if (image == null) { return 0; } else { float w = image.getWidth(); float h = image.getHeight(); return (int)(w * height / h); } }
/** * 获取自动缩放后的高度 * @author Administrator * @param url * @param width * @return */ public static int getAutoZoomHeightByWidth(String url, int width) { Image image = getImageFromUrl(url); if (image == null) { return 0; } else { float w = image.getWidth(); float h = image.getHeight(); return (int)(h * width / w); } }