Search in sources :

Example 16 with Image

use of com.itextpdf.text.Image in project trainning by fernandotomasio.

the class DOC002PDF method buildFrontispicio.

private void buildFrontispicio(Document document, CurriculoMinimoDTO curriculoMinimo) throws DocumentException {
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    Paragraph p1 = new Paragraph();
    p1.setAlignment(Element.ALIGN_CENTER);
    p1.add(new Phrase("MINISTÉRIO DA DEFESA", fontManager.getH1Font()));
    document.add(p1);
    Paragraph p2 = new Paragraph();
    p2.setAlignment(Element.ALIGN_CENTER);
    p2.add(new Phrase("COMANDO DA AERONÁUTICA", fontManager.getH1Font()));
    document.add(p2);
    Paragraph p3 = new Paragraph();
    p3.setAlignment(Element.ALIGN_CENTER);
    p3.add(new Phrase("DEPARTAMENTO DE CONTROLE DO ESPAÇO AÉREO", fontManager.getDefaultFont()));
    document.add(p3);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    try {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = classLoader.getResource("aer.png").getPath();
        Image image = Image.getInstance(path);
        image.setAlignment(Element.ALIGN_CENTER);
        image.scalePercent(18);
        document.add(image);
    } catch (BadElementException | IOException ex) {
        Logger.getLogger(DOC001PDF.class.getName()).log(Level.SEVERE, null, ex);
    }
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    Paragraph p4 = new Paragraph();
    p4.setAlignment(Element.ALIGN_CENTER);
    p4.add(new Phrase("ENSINO", fontManager.getH1Font()));
    document.add(p4);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
    PdfPTable t = new PdfPTable(1);
    PdfPCell unica = new PdfPCell();
    unica.setPadding(10);
    // Paragraph p5 = new Paragraph();
    // p5.setAlignment(Element.ALIGN_CENTER);
    // p5.add(new Phrase("ICA 56-3", fontManager.getDefaultFont()));
    // p5.add(Chunk.NEWLINE);
    Paragraph p6 = new Paragraph();
    p6.setAlignment(Element.ALIGN_CENTER);
    // p6.add(new Phrase(curriculoMinimo.getCurso().getDescricao(), fontManager.getDefaultFont()));
    // Paragraph p7 = new Paragraph();
    // p7.setAlignment(Element.ALIGN_CENTER);
    // p7.add(new Phrase("PLANO DE UNIDADES DIDÁTICAS DO CURSO " + curriculoMinimo.getCurso().getCodigo(), fontManager.getDefaultFont()));
    // Paragraph p8 = new Paragraph();
    // p8.setAlignment(Element.ALIGN_CENTER);
    // p8.add(new Phrase(curriculoMinimo.getAnoPublicacaoPUD(), fontManager.getDefaultFont()));
    p6.add(new Phrase("PLANO DE UNIDADES DIDÁTICAS DO CURSO " + curriculoMinimo.getCurso().getDescricao(), fontManager.getDefaultFont()));
    Paragraph p7 = new Paragraph();
    p7.setAlignment(Element.ALIGN_CENTER);
    p7.add(new Phrase(curriculoMinimo.getCurso().getCodigo(), fontManager.getDefaultFont()));
    Paragraph p8 = new Paragraph();
    p8.setAlignment(Element.ALIGN_CENTER);
    p8.add(new Phrase(curriculoMinimo.getAnoPublicacaoPUD(), fontManager.getDefaultFont()));
    // unica.addElement(p5);
    unica.addElement(Chunk.NEWLINE);
    unica.addElement(p6);
    unica.addElement(p7);
    unica.addElement(Chunk.NEWLINE);
    unica.addElement(p8);
    unica.addElement(Chunk.NEWLINE);
    t.addCell(unica);
    document.add(t);
    // document.add(Chunk.NEXTPAGE);
    // 
    // document.add(buildPrefacio(curriculoMinimo));
    document.add(Chunk.NEXTPAGE);
    document.add(Chunk.NEWLINE);
    document.add(Chunk.NEWLINE);
}
Also used : PdfPCell(com.itextpdf.text.pdf.PdfPCell) PdfPTable(com.itextpdf.text.pdf.PdfPTable) BadElementException(com.itextpdf.text.BadElementException) Phrase(com.itextpdf.text.Phrase) IOException(java.io.IOException) Image(com.itextpdf.text.Image) Paragraph(com.itextpdf.text.Paragraph)

Example 17 with Image

use of com.itextpdf.text.Image in project trainning by fernandotomasio.

the class ReportUtil method setBackground.

public byte[] setBackground(byte[] documentSource, String url) {
    PdfReader reader = null;
    PdfStamper stamp = null;
    ByteArrayOutputStream byteArray = null;
    try {
        byteArray = new ByteArrayOutputStream();
        reader = new PdfReader(documentSource);
        int n = reader.getNumberOfPages();
        // Create a stamper that will copy the document to a new file
        stamp = new PdfStamper(reader, byteArray);
        int i = 1;
        PdfContentByte under;
        PdfContentByte over;
        Image image = Image.getInstance(url);
        image.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
        image.setAbsolutePosition(0, 0);
        // image.setAbsolutePosition(200, 400);
        while (i <= n) {
            // Watermark under the existing page
            under = stamp.getUnderContent(i);
            under.addImage(image);
            // Text over the existing page
            // over = stamp.getOverContent(i);
            // over.beginText();
            // over.setFontAndSize(bf, 18);
            // over.showText("page " + i);
            // over.endText();
            i++;
        }
        stamp.close();
    } catch (DocumentException ex) {
        Logger.getLogger(ReportUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return byteArray.toByteArray();
}
Also used : PdfStamper(com.itextpdf.text.pdf.PdfStamper) DocumentException(com.itextpdf.text.DocumentException) PdfContentByte(com.itextpdf.text.pdf.PdfContentByte) PdfReader(com.itextpdf.text.pdf.PdfReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Image(com.itextpdf.text.Image)

Example 18 with Image

use of com.itextpdf.text.Image in project TranskribusCore by Transkribus.

the class TrpPdfDocument method addPage.

@SuppressWarnings("unused")
public void addPage(URL imgUrl, TrpDoc doc, PcGtsType pc, boolean addAdditionalPlainTextPage, boolean imageOnly, FimgStoreImgMd md, boolean doBlackening, ExportCache cache) throws MalformedURLException, IOException, DocumentException, JAXBException, URISyntaxException {
    imgOnly = imageOnly;
    extraTextPage = addAdditionalPlainTextPage;
    // FIXME use this only on cropped (printspace) images!!
    java.awt.Rectangle printspace = null;
    // if(pc.getPage() != null && pc.getPage().getPrintSpace() != null){
    // java.awt.Polygon psPoly = PageXmlUtils.buildPolygon(pc.getPage().getPrintSpace().getCoords());
    // printspace = psPoly.getBounds();
    // }
    BufferedImage imgBuffer = null;
    try (InputStream input = imgUrl.openStream()) {
        imgBuffer = ImageIO.read(input);
    } catch (FileNotFoundException e) {
        logger.error("File was not found at url " + imgUrl);
        URL origUrl = new URL(imgUrl.getProtocol(), imgUrl.getHost(), imgUrl.getFile().replace("view", "orig"));
        logger.debug("try orig file location " + origUrl);
        try (InputStream input = origUrl.openStream()) {
            imgBuffer = ImageIO.read(input);
        }
    }
    Graphics2D graph = imgBuffer.createGraphics();
    graph.setColor(Color.BLACK);
    List<TrpRegionType> regions = pc.getPage().getTextRegionOrImageRegionOrLineDrawingRegion();
    // regions should be sorted after their reading order at this point - so no need to resort
    // Collections.sort(regions, new TrpElementCoordinatesComparator<RegionType>());
    int nrOfTextRegions = 0;
    for (RegionType r : regions) {
        // used later to decide if new page is necessary if there is at least one text region
        if (r instanceof TextRegionType) {
            nrOfTextRegions++;
        } else if (r instanceof UnknownRegionType && doBlackening) {
            UnknownRegionType urt = (UnknownRegionType) r;
            ITrpShapeType trpShape = (ITrpShapeType) r;
            boolean isBlackening = RegionTypeUtil.isBlackening(trpShape);
            if (isBlackening) {
                // Rectangle blackRect = (Rectangle) PageXmlUtils.buildPolygon(urt.getCoords().getPoints()).getBounds();
                Rectangle blackRect = urt.getBoundingBox();
                graph.fillRect((int) blackRect.getMinX(), (int) blackRect.getMinY(), (int) blackRect.getWidth(), (int) blackRect.getHeight());
            }
        }
    }
    graph.dispose();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(imgBuffer, "JPEG", baos);
    byte[] imageBytes = baos.toByteArray();
    Image img = Image.getInstance(imageBytes);
    baos.close();
    imgBuffer.flush();
    imgBuffer = null;
    /*
		 * take resolution from metadata of image store, values in img are not always set
		 */
    if (md != null) {
        double resolutionX = (float) md.getXResolution();
        double resolutionY = (float) md.getYResolution();
        // logger.debug("Dpi: " + md.getXResolution());
        img.setDpi((int) resolutionX, (int) resolutionY);
    }
    // else{
    // 
    // Image img = Image.getInstance(imgUrl);
    // }
    int cutoffLeft = 0;
    int cutoffTop = 0;
    if (printspace == null) {
        /*
			 * 1 Punkt pro cm  = 2,54 dpi
			 * img.getPlainWidth() = horizontal size in Pixel
			 * img.getPlainHeight() = vertical size in Pixel
			 * img.getDpiX() = resolution of x direction
			 * Size in cm: img.getDpiX() / (img.getDpiX()/2,54)
			 */
        // logger.debug("Horizontal size in cm: img.getPlainWidth() / (img.getDpiX()/2,54): " + img.getPlainWidth() / (img.getDpiX()/2.54));
        // logger.debug("Vertical size in cm: img.getPlainHeight() / (img.getDpiY()/2,54): " + img.getPlainHeight() / (img.getDpiY()/2.54));
        setPageSize(img);
    } else {
        int width = (int) printspace.getWidth();
        int height = (int) printspace.getHeight();
        setPageSize(new com.itextpdf.text.Rectangle(width, height));
        cutoffLeft = printspace.x;
        cutoffTop = printspace.y;
    }
    float xSize;
    float ySize;
    /*
		 * calculate size of image with respect to Dpi of the image and the default points of PDF which is 72
		 * PDF also uses the same basic measurement unit as PostScript: 72 points == 1 inch
		 */
    if (img.getDpiX() > 72f) {
        xSize = (float) (img.getPlainWidth() / img.getDpiX() * 72);
        ySize = (float) (img.getPlainHeight() / img.getDpiY() * 72);
        scaleFactorX = scaleFactorY = (float) (72f / img.getDpiX());
    } else {
        xSize = (float) (img.getPlainWidth() / 300 * 72);
        ySize = (float) (img.getPlainHeight() / 300 * 72);
        scaleFactorX = scaleFactorY = 72f / 300;
    }
    /*
		 * construct the grid for the added page
		 */
    for (int i = 0; i <= 12; i++) {
        twelfthPoints[i][0] = i * (img.getPlainWidth() / 12);
        twelfthPoints[i][1] = i * (img.getPlainHeight() / 12);
    }
    // TODO use scaleToFit instead?
    img.scaleAbsolute(xSize, ySize);
    img.setAbsolutePosition(0, 0);
    /*
		 * calculate physical size of image in inch and assign text size dependent on these values
		 */
    if (img.getScaledWidth() / 72f < 9 && img.getScaledHeight() / 72f < 12) {
        lineMeanHeight = 12 / scaleFactorY;
    } else {
        lineMeanHeight = 17 / scaleFactorY;
    }
    if (doc != null && createTitle) {
        addTitlePage(doc);
        // logger.debug("page number " + getPageNumber());
        if (getPageNumber() % 1 != 0) {
            logger.debug("odd page number -> add one new page");
            document.newPage();
            // necessary that an empty page can be created
            writer.setPageEmpty(false);
        }
    }
    document.newPage();
    addTextAndImage(pc, cutoffLeft, cutoffTop, img, imageOnly, cache);
    if (addAdditionalPlainTextPage) {
        if (nrOfTextRegions > 0) {
            logger.debug("add uniform text");
            document.newPage();
            addUniformText(pc, cutoffLeft, cutoffTop, cache);
        }
    }
}
Also used : Rectangle(java.awt.Rectangle) TrpTextRegionType(eu.transkribus.core.model.beans.pagecontent_trp.TrpTextRegionType) UnknownRegionType(eu.transkribus.core.model.beans.pagecontent.UnknownRegionType) TrpRegionType(eu.transkribus.core.model.beans.pagecontent_trp.TrpRegionType) TrpTableRegionType(eu.transkribus.core.model.beans.pagecontent_trp.TrpTableRegionType) RegionType(eu.transkribus.core.model.beans.pagecontent.RegionType) TextRegionType(eu.transkribus.core.model.beans.pagecontent.TextRegionType) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) Rectangle(java.awt.Rectangle) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedImage(java.awt.image.BufferedImage) Image(com.itextpdf.text.Image) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) Point(java.awt.Point) ITrpShapeType(eu.transkribus.core.model.beans.pagecontent_trp.ITrpShapeType) Graphics2D(java.awt.Graphics2D) TrpTextRegionType(eu.transkribus.core.model.beans.pagecontent_trp.TrpTextRegionType) TextRegionType(eu.transkribus.core.model.beans.pagecontent.TextRegionType) UnknownRegionType(eu.transkribus.core.model.beans.pagecontent.UnknownRegionType) TrpRegionType(eu.transkribus.core.model.beans.pagecontent_trp.TrpRegionType)

Example 19 with Image

use of com.itextpdf.text.Image in project spring-cloud-digital-sign by SpringForAll.

the class Sign method sign.

/**
 * 单多次签章通用
 * @param src string source pdf
 * @param target string target pdf
 * @param signatureInfos SignatureInfo
 */
public static void sign(String src, String target, SignatureInfo... signatureInfos) {
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    try {
        inputStream = new FileInputStream(src);
        for (SignatureInfo signatureInfo : signatureInfos) {
            ByteArrayOutputStream tempArrayOutputStream = new ByteArrayOutputStream();
            PdfReader reader = new PdfReader(inputStream);
            // 创建签章工具PdfStamper ,最后一个boolean参数是否允许被追加签名
            PdfStamper stamper = PdfStamper.createSignature(reader, tempArrayOutputStream, '\0', null, true);
            // 获取数字签章属性对象
            PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
            appearance.setReason(signatureInfo.getReason());
            appearance.setLocation(signatureInfo.getLocation());
            // 设置签名的签名域名称,多次追加签名的时候,签名预名称不能一样,图片大小受表单域大小影响(过小导致压缩)
            appearance.setVisibleSignature(signatureInfo.getFieldName());
            // 读取图章图片
            Image image = Image.getInstance(signatureInfo.getImagePath());
            appearance.setSignatureGraphic(image);
            appearance.setCertificationLevel(signatureInfo.getCertificationLevel());
            // 设置图章的显示方式,如下选择的是只显示图章(还有其他的模式,可以图章和签名描述一同显示)
            appearance.setRenderingMode(signatureInfo.getRenderingMode());
            /**
             * 粘贴图片
             */
            // PdfContentByte over = stamper.getOverContent(1);
            // image.setAbsolutePosition(0 , 0);
            // image.scaleToFit(300 , 109);
            // over.addImage(image);
            // 摘要算法
            ExternalDigest digest = new BouncyCastleDigest();
            // 签名算法
            ExternalSignature signature = new PrivateKeySignature(signatureInfo.getPk(), signatureInfo.getDigestAlgorithm(), null);
            // 调用itext签名方法完成pdf签章
            MakeSignature.signDetached(appearance, digest, signature, signatureInfo.getChain(), null, null, null, 0, signatureInfo.getSubfilter());
            // 定义输入流为生成的输出流内容,以完成多次签章的过程
            inputStream = new ByteArrayInputStream(tempArrayOutputStream.toByteArray());
            result = tempArrayOutputStream;
        }
        outputStream = new FileOutputStream(new File(target));
        outputStream.write(result.toByteArray());
        outputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != outputStream) {
                outputStream.close();
            }
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != result) {
                result.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : PdfSignatureAppearance(com.itextpdf.text.pdf.PdfSignatureAppearance) PdfReader(com.itextpdf.text.pdf.PdfReader) Image(com.itextpdf.text.Image) PdfStamper(com.itextpdf.text.pdf.PdfStamper)

Example 20 with Image

use of com.itextpdf.text.Image in project digilib by robcast.

the class PDFTitlePage method getLogo.

/*
	 * Methods for the different attributes.
	 * 
	 */
private Image getLogo() {
    try {
        URL url = new URL(job_info.getDlConfig().getAsString("pdf-logo"));
        if (url != null && !url.equals("")) {
            Image logo = Image.getInstance(url);
            logo.setAlignment(Element.ALIGN_CENTER);
            return logo;
        }
    } catch (BadElementException e) {
        logger.error(e.getMessage());
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) BadElementException(com.itextpdf.text.BadElementException) IOException(java.io.IOException) Image(com.itextpdf.text.Image) URL(java.net.URL)

Aggregations

Image (com.itextpdf.text.Image)20 PdfPCell (com.itextpdf.text.pdf.PdfPCell)10 IOException (java.io.IOException)10 BadElementException (com.itextpdf.text.BadElementException)7 Phrase (com.itextpdf.text.Phrase)7 Paragraph (com.itextpdf.text.Paragraph)5 BufferedImage (java.awt.image.BufferedImage)5 DocumentException (com.itextpdf.text.DocumentException)3 PdfContentByte (com.itextpdf.text.pdf.PdfContentByte)3 PdfPTable (com.itextpdf.text.pdf.PdfPTable)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Font (com.itextpdf.text.Font)2 PdfReader (com.itextpdf.text.pdf.PdfReader)2 PdfStamper (com.itextpdf.text.pdf.PdfStamper)2 KpiVO (com.netsteadfast.greenstep.vo.KpiVO)2 ObjectiveVO (com.netsteadfast.greenstep.vo.ObjectiveVO)2 PerspectiveVO (com.netsteadfast.greenstep.vo.PerspectiveVO)2 URL (java.net.URL)2 BaseColor (com.itextpdf.text.BaseColor)1 Document (com.itextpdf.text.Document)1