Search in sources :

Example 1 with PdfStamper

use of com.itextpdf.text.pdf.PdfStamper in project portal by ixinportal.

the class PDFUtils method readPDF2.

public static ByteArrayOutputStream readPDF2(InputStream is, String enterpriseName, String keySn, String certSn, String mPhone) throws Exception {
    // 模版文件目录
    PdfReader reader = new PdfReader(is);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    PdfStamper ps = new PdfStamper(reader, bos);
    AcroFields s = ps.getAcroFields();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    s.setFieldProperty("enterpriseName", "textfont", bfChinese, null);
    s.setFieldProperty("mPhone", "textfont", bfChinese, null);
    s.setFieldProperty("keySn", "textfont", bfChinese, null);
    s.setFieldProperty("certSn", "textfont", bfChinese, null);
    s.setFieldProperty("nowdate", "textfont", bfChinese, null);
    s.setField("enterpriseName", enterpriseName);
    s.setField("keySn", keySn);
    s.setField("certSn", certSn);
    s.setField("mPhone", mPhone);
    s.setField("nowdate", format.format(new Date()));
    // 这句不能少
    ps.setFormFlattening(true);
    ps.close();
    reader.close();
    return bos;
}
Also used : PdfStamper(com.itextpdf.text.pdf.PdfStamper) AcroFields(com.itextpdf.text.pdf.AcroFields) BaseFont(com.itextpdf.text.pdf.BaseFont) PdfReader(com.itextpdf.text.pdf.PdfReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 2 with PdfStamper

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

the class PkxSign method sign.

public static void sign() throws Exception {
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(cert_path), cert_pwd.toCharArray());
    String alias = (String) ks.aliases().nextElement();
    // PrivateKey pk = (PrivateKey) ks.getKey(alias, cert_pwd.toCharArray());
    // KeyStore ks = KeyStore.getInstance("PKCS12");
    // ks.load(new FileInputStream(cert_path), cert_pwd.toCharArray());
    PkxSign sign = new PkxSign();
    PrivateKey pk = sign.GetPvkformPfx(cert_path, cert_pwd);
    Certificate[] chain = ks.getCertificateChain(alias);
    PdfReader reader = new PdfReader(source_pdf);
    FileOutputStream os = new FileOutputStream(output_pdf);
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason("digtal signature");
    appearance.setLocation("FuZhou");
    appearance.setVisibleSignature(new Rectangle(0, 300, 300, 109), 1, "sig");
// Creating the signature
// ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, provider.getName());
// ExternalDigest digest = new BouncyCastleDigest();
// MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
}
Also used : Rectangle(com.itextpdf.text.Rectangle) PdfSignatureAppearance(com.itextpdf.text.pdf.PdfSignatureAppearance) PdfReader(com.itextpdf.text.pdf.PdfReader) PdfStamper(com.itextpdf.text.pdf.PdfStamper) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Certificate(java.security.cert.Certificate)

Example 3 with PdfStamper

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

the class BuilderController method makeArea.

/**
 * build signature area in pdf file
 * @param signatureAreaPattern params
 * @return String
 */
public ResponseEntity<?> makeArea(@RequestBody SignatureAreaPattern signatureAreaPattern) {
    try {
        String fileResultName = signatureAreaPattern.getTmpFile() + "out";
        PdfReader pdfReader = new PdfReader(keyStoreSavePath + "/" + signatureAreaPattern.getTmpFile());
        FileOutputStream out = new FileOutputStream(tmpDir + "/" + fileResultName);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, out);
        pdfStamper.addSignature(signatureAreaPattern.getName(), signatureAreaPattern.getPageNumber(), signatureAreaPattern.getFirstX().floatValue(), signatureAreaPattern.getFirstY().floatValue(), signatureAreaPattern.getSecondX().floatValue(), signatureAreaPattern.getSecondY().floatValue());
        pdfStamper.close();
        fileUtil.deleteFile(tmpDir + "/" + signatureAreaPattern.getTmpFile());
        return ResponseEntity.ok(fileResultName);
    } catch (Exception e) {
        System.out.println("maybe not builder's job....");
        e.printStackTrace();
        return null;
    }
}
Also used : PdfStamper(com.itextpdf.text.pdf.PdfStamper) FileOutputStream(java.io.FileOutputStream) PdfReader(com.itextpdf.text.pdf.PdfReader)

Example 4 with PdfStamper

use of com.itextpdf.text.pdf.PdfStamper in project trainning by fernandotomasio.

the class DOC003PDF method makeReport.

@Override
public void makeReport() {
    teachingDocumentsService = (TeachingDocumentsService) services.get("teachingDocumentsService");
    document = documentManager.getDocumentPortrait();
    os = documentManager.prepareDocument(document);
    writer = documentManager.getWritter();
    ChapterSectionTOC eventHandler = new ChapterSectionTOC();
    writer.setPageEvent(eventHandler);
    document.open();
    CSSResolver cssResolver = new StyleAttrCSSResolver();
    CssFile cssFile = null;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String cssStylePath = classLoader.getResource("doc3-styles.css").getPath();
    cssFile = XMLWorkerHelper.getCSS(classLoader.getResourceAsStream("doc3-styles.css"));
    cssResolver.addCss(cssFile);
    XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
    String fontFilePath = classLoader.getResource("MyriadPro-Regular.otf").getPath();
    // fontProvider.register(fontFilePath);
    CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
    htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
    PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
    HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
    XMLWorker worker = new XMLWorker(css, true);
    p = new XMLParser(worker);
    try {
        String apostilaIdParam = (String) params.get("apostilaId");
        Long apostilaId = Long.parseLong(apostilaIdParam);
        ApostilaDTO apostila = teachingDocumentsService.findApostila(apostilaId);
        CurriculoMinimoDTO curriculo = teachingDocumentsService.findCurriculoMinimo(apostila.getDisciplina().getCurriculoMinimo().getId());
        buildCover(document, curriculo, apostila);
        CapituloApostilaDTO[] capitulos = teachingDocumentsService.findAllCapitulosApostila(apostilaId);
        for (CapituloApostilaDTO capitulo : capitulos) {
            Chapter ch = buildCapitulo(capitulo, p, document);
            document.add(ch);
        }
        document.add(buildReferencias(apostilaId));
        document.add(buildSumario(eventHandler.titles));
    } catch (DocumentException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
        throw new CoreException(e.getMessage());
    } catch (IOException ex) {
        Logger.getLogger(DOC003PDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        document.close();
    }
    try {
        PdfReader reader = new PdfReader(os.toByteArray());
        int n = reader.getNumberOfPages();
        String pagesInterval = String.format("1-2,%d, 3-%d", n, n - 1);
        reader.selectPages(pagesInterval);
        os = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, os);
        stamper.close();
        reader.close();
    } catch (IOException | DocumentException ex) {
        Logger.getLogger(DOC003PDF.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : StyleAttrCSSResolver(com.itextpdf.tool.xml.css.StyleAttrCSSResolver) CssFile(com.itextpdf.tool.xml.css.CssFile) PdfReader(com.itextpdf.text.pdf.PdfReader) CssAppliersImpl(com.itextpdf.tool.xml.html.CssAppliersImpl) CSSResolver(com.itextpdf.tool.xml.pipeline.css.CSSResolver) StyleAttrCSSResolver(com.itextpdf.tool.xml.css.StyleAttrCSSResolver) DocumentException(com.itextpdf.text.DocumentException) CapituloApostilaDTO(com.tomasio.projects.trainning.dto.CapituloApostilaDTO) CurriculoMinimoDTO(com.tomasio.projects.trainning.dto.CurriculoMinimoDTO) XMLParser(com.itextpdf.tool.xml.parser.XMLParser) HtmlPipeline(com.itextpdf.tool.xml.pipeline.html.HtmlPipeline) SecaoApostilaDTO(com.tomasio.projects.trainning.dto.SecaoApostilaDTO) ApostilaDTO(com.tomasio.projects.trainning.dto.ApostilaDTO) CapituloApostilaDTO(com.tomasio.projects.trainning.dto.CapituloApostilaDTO) Chapter(com.itextpdf.text.Chapter) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CssResolverPipeline(com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline) XMLWorkerFontProvider(com.itextpdf.tool.xml.XMLWorkerFontProvider) XMLWorker(com.itextpdf.tool.xml.XMLWorker) CoreException(com.tomasio.projects.trainning.exeption.CoreException) CssAppliers(com.itextpdf.tool.xml.html.CssAppliers) PdfWriterPipeline(com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline) PdfStamper(com.itextpdf.text.pdf.PdfStamper) HtmlPipelineContext(com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext)

Example 5 with PdfStamper

use of com.itextpdf.text.pdf.PdfStamper in project trainning by fernandotomasio.

the class DOC002PDF method makeReport.

@Override
public void makeReport() {
    teachingDocumentsService = (TeachingDocumentsService) services.get("teachingDocumentsService");
    document = documentManager.getDocumentPortrait();
    os = documentManager.prepareDocument(document);
    writer = documentManager.getWritter();
    ChapterSectionTOC eventHandler = new ChapterSectionTOC();
    writer.setPageEvent(eventHandler);
    document.open();
    try {
        String curriculoMinimoIdParam = (String) params.get("curriculoMinimoId");
        Long curriculoMinimoId = Long.parseLong(curriculoMinimoIdParam);
        CurriculoMinimoDTO curriculoMinimo = teachingDocumentsService.findCurriculoMinimo(curriculoMinimoId);
        buildCover(document, curriculoMinimo);
        buildFrontispicio(document, curriculoMinimo);
        document.add(buildPrefacio(curriculoMinimo));
        document.add(Chunk.NEXTPAGE);
        document.add(buildAbreviaturas(curriculoMinimo));
        document.add(Chunk.NEXTPAGE);
        document.add(buildDisposicoesPreliminares(curriculoMinimo));
        document.add(Chunk.NEXTPAGE);
        document.add(buildAtividadesComplementares(curriculoMinimo));
        document.add(Chunk.NEXTPAGE);
        document.add(buildComplementacaoInstrucao(curriculoMinimo));
        document.add(Chunk.NEXTPAGE);
        // PdfPTable tableAtividadesAvaliativas = buildAtividadesAvaliativasTable(curriculoMinimo);
        // document.add(tableAtividadesAvaliativas);
        Paragraph p12 = new Paragraph();
        p12.add(new Phrase("4 DETALHAMENTO DAS UNIDADES DIDÁTICAS", fontManager.getBoldFont()));
        document.add(p12);
        document.add(Chunk.NEWLINE);
        DisciplinaDTO[] disciplinas = teachingDocumentsService.findAllDisciplinasByCurriculoMinimo(curriculoMinimo.getId());
        for (DisciplinaDTO disciplina : disciplinas) {
            PdfPTable tableDisciplina = buildTableDisciplina(disciplina);
            document.add(tableDisciplina);
            document.add(Chunk.NEWLINE);
            UnidadeDidaticaDTO[] unidades = teachingDocumentsService.findAllUnidadesDidaticas(disciplina.getId());
            PdfPTable unidadesHeaderTable = new PdfPTable(1);
            unidadesHeaderTable.setWidthPercentage(100);
            PdfPCell p20 = new PdfPCell(new Phrase("UNIDADES DIDÁTICAS", fontManager.getBoldFont()));
            unidadesHeaderTable.addCell(p20);
            unidadesHeaderTable.setHorizontalAlignment(Element.ALIGN_CENTER);
            document.add(unidadesHeaderTable);
            document.add(Chunk.NEWLINE);
            for (UnidadeDidaticaDTO unidade : unidades) {
                PdfPTable tableUnidade = buildTableUnidade(unidade);
                document.add(tableUnidade);
                document.add(Chunk.NEWLINE);
            }
            PdfPTable tableRecomendacoes = buildTableRecomendacoesMetodologicas(disciplina);
            document.add(tableRecomendacoes);
            document.add(Chunk.NEWLINE);
            PdfPTable perfisTable = buildTablePerfisRelacionamento(disciplina);
            document.add(perfisTable);
            document.add(Chunk.NEWLINE);
            PdfPTable referenciasTable = buildTableReferencias(disciplina);
            document.add(referenciasTable);
            document.add(Chunk.NEXTPAGE);
        }
        document.add(Chunk.NEXTPAGE);
        document.add(buildDisposicoesFinais(curriculoMinimo));
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);
        document.add(buildAssinatura());
        document.add(Chunk.NEXTPAGE);
        document.add(buildSumario(eventHandler.titles));
    } catch (DocumentException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
        throw new CoreException(e.getMessage());
    } finally {
        document.close();
    }
    try {
        PdfReader reader = new PdfReader(os.toByteArray());
        int n = reader.getNumberOfPages();
        String pagesInterval = String.format("1-4,%d, 5-%d", n, n - 1);
        reader.selectPages(pagesInterval);
        os = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, os);
        stamper.close();
        reader.close();
    } catch (IOException ex) {
        Logger.getLogger(DOC002PDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(DOC002PDF.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        PdfReader reader = new PdfReader(os.toByteArray());
        os = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, os);
        int total = reader.getNumberOfPages();
        PdfContentByte over = null;
        int total_pages = total - 1;
        for (int i = 1; i < total; i++) {
            int actual_page = i - 1;
            if (i > 5) {
                over = stamper.getOverContent(i);
                System.out.println(over);
                over.beginText();
                BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, "UTF-8", false);
                over.setFontAndSize(baseFont, 12);
                if ((i % 2) == 0) {
                    over.showTextAligned(PdfContentByte.ALIGN_RIGHT, actual_page + "/" + total_pages, 538, 803, 0);
                } else {
                    over.showTextAligned(PdfContentByte.ALIGN_LEFT, actual_page + "/" + total_pages, 58, 803, 0);
                }
                over.endText();
            }
        }
        // PdfContentByte content = stamper.getOverContent(1);
        // ColumnText ct = new ColumnText( content );
        // ct.setSimpleColumn(50,50,50,50);
        // ct.setText(new Phrase("TESTANDO"));
        // ct.go();
        stamper.close();
        reader.close();
    } catch (IOException ex) {
    // Logger.getLogger(DOC001PDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(DOC001PDF.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : PdfPCell(com.itextpdf.text.pdf.PdfPCell) Phrase(com.itextpdf.text.Phrase) PdfReader(com.itextpdf.text.pdf.PdfReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) UnidadeDidaticaDTO(com.tomasio.projects.trainning.dto.UnidadeDidaticaDTO) ObjetivoUnidadeDidaticaDTO(com.tomasio.projects.trainning.dto.ObjetivoUnidadeDidaticaDTO) Paragraph(com.itextpdf.text.Paragraph) PdfPTable(com.itextpdf.text.pdf.PdfPTable) CoreException(com.tomasio.projects.trainning.exeption.CoreException) PdfStamper(com.itextpdf.text.pdf.PdfStamper) DocumentException(com.itextpdf.text.DocumentException) DisciplinaDTO(com.tomasio.projects.trainning.dto.DisciplinaDTO) ObjetivoDisciplinaDTO(com.tomasio.projects.trainning.dto.ObjetivoDisciplinaDTO) BaseFont(com.itextpdf.text.pdf.BaseFont) CurriculoMinimoDTO(com.tomasio.projects.trainning.dto.CurriculoMinimoDTO) PdfContentByte(com.itextpdf.text.pdf.PdfContentByte)

Aggregations

PdfReader (com.itextpdf.text.pdf.PdfReader)9 PdfStamper (com.itextpdf.text.pdf.PdfStamper)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 DocumentException (com.itextpdf.text.DocumentException)3 AcroFields (com.itextpdf.text.pdf.AcroFields)3 BaseFont (com.itextpdf.text.pdf.BaseFont)3 IOException (java.io.IOException)3 SimpleDateFormat (java.text.SimpleDateFormat)3 Date (java.util.Date)3 Image (com.itextpdf.text.Image)2 PdfContentByte (com.itextpdf.text.pdf.PdfContentByte)2 PdfSignatureAppearance (com.itextpdf.text.pdf.PdfSignatureAppearance)2 CurriculoMinimoDTO (com.tomasio.projects.trainning.dto.CurriculoMinimoDTO)2 CoreException (com.tomasio.projects.trainning.exeption.CoreException)2 FileOutputStream (java.io.FileOutputStream)2 Chapter (com.itextpdf.text.Chapter)1 Paragraph (com.itextpdf.text.Paragraph)1 Phrase (com.itextpdf.text.Phrase)1 Rectangle (com.itextpdf.text.Rectangle)1 PdfPCell (com.itextpdf.text.pdf.PdfPCell)1