Example usage for com.lowagie.text.pdf PdfCopyFields addDocument

List of usage examples for com.lowagie.text.pdf PdfCopyFields addDocument

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfCopyFields addDocument.

Prototype

public void addDocument(PdfReader reader) throws DocumentException, IOException 

Source Link

Document

Concatenates a PDF document.

Usage

From source file:ErrMsgException.java

License:Open Source License

public static void main(String args[]) {
    // ?//from   w ww  .  j a  va  2s.  co m
    if (args.length < 3 || args.length > 5) {
        usage();
        return;
    }

    // ??
    ArrayList<HashMap> bookmark = new ArrayList<HashMap>();
    HashMap<String, Object> lastmap = null;
    ArrayDeque<ArrayList> queue = new ArrayDeque<ArrayList>();
    queue.push(bookmark);

    // ?????
    try {
        File file = new File(args[2]);
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        int previouslevel = 0;
        int lno = 0;

        while ((line = br.readLine()) != null) {
            lno++;
            if (line.startsWith("#"))
                continue; // ?#

            int level = 0;
            if (line.startsWith("\t")) {
                // 
                do {
                    line = line.substring(1);
                    level++;
                } while (line.startsWith("\t"));
            }

            String lines[] = line.split("\t");
            line = "";
            if (lines.length > 2) {
                for (int i = 0; i < lines.length - 1; i++) {
                    line += lines[i];
                    if (i < lines.length - 1)
                        line += "";
                }
            } else {
                line = lines[0];
            }
            if (lines.length < 2)
                continue;

            int preample = 0;
            if (args.length >= 4) {
                preample = Integer.parseInt(args[3]);
            }
            int page = roman2arabic(lines[lines.length - 1], preample);

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("Title", line);
            map.put("Action", "GoTo");
            map.put("Page", page + " Fit");

            if (args.length >= 5) {
                // ??
                int foldlevel = Integer.parseInt(args[4]);
                if (foldlevel <= level)
                    map.put("Open", "false");
            }

            if (level > previouslevel) {
                if (level - previouslevel > 1) {
                    // ???
                    throw new ErrMsgException(
                            lno + ": ??2?????????");
                }
                // 
                ArrayList<HashMap> kids = new ArrayList<HashMap>();
                kids.add(map);
                if (lastmap != null) {
                    lastmap.put("Kids", kids);
                } else {
                    throw new ErrMsgException(
                            lno + ": ??????????");
                }
                queue.push(kids);

            } else if (level < previouslevel) {
                // ?
                for (int i = previouslevel; i > level; i--) {
                    queue.pop();
                }
                queue.peek().add(map);
            } else {
                // ????????
                queue.peek().add(map);
            }
            lastmap = map;
            previouslevel = level;
        }

        br.close();
    } catch (IOException e) {
        System.out.println(e);
        return;
    } catch (ErrMsgException e) {
        System.out.println("?????\n" + e.getMessage());
        return;
    }

    // PDF????
    try {
        PdfReader reader = new PdfReader(args[0]);
        int maxpage = reader.getNumberOfPages();

        OutputStream os = new FileOutputStream(args[1]);
        PdfCopyFields copyFields = new PdfCopyFields(os);
        copyFields.addDocument(reader);

        copyFields.setOutlines(bookmark);

        if (args.length > 3) { // ?
            PdfPageLabels labels = new PdfPageLabels();
            if (maxpage > 0)
                labels.addPageLabel(1, PdfPageLabels.LOWERCASE_ROMAN_NUMERALS, null, 1);
            if (maxpage > Integer.parseInt(args[3]))
                labels.addPageLabel(Integer.parseInt(args[3]) + 1, PdfPageLabels.DECIMAL_ARABIC_NUMERALS, null,
                        1);

            copyFields.getWriter().setPageLabels(labels);
        }

        copyFields.close();
        os.close();
    } catch (DocumentException e) {
        System.out.println(e);
        return;
    } catch (IOException e) {
        System.out.println(e);
        return;
    }
    System.out.println(args[1] + " ?????");
}

From source file:cn.hanbell.rpt.control.ReportManagedBean.java

@Override
public void print() throws Exception {
    String system = paramMap.get("system")[0];
    String api = paramMap.get("api")[0];
    systemProgram = systemProgramBean.findBySystemAndAPI(system, api);
    if (systemProgram == null) {
        FacesContext.getCurrentInstance().getExternalContext().redirect("deny.xhtml");
    }//from ww w . j a  v a  2  s .  c  o m
    HashMap<String, Object> reportParams = new HashMap<>();
    reportParams.put("JNDIName", systemProgram.getRptjndi());
    if (paramMap.containsKey("formid")) {
        if ("EFGP".equals(system)) {
            ProcessInstance pi = processInstanceBean.findByOID(paramMap.get("formid")[0]);
            reportParams.put("formid", pi.getSerialNumber());
        } else {
            reportParams.put("formid", paramMap.get("formid")[0]);
        }
    }
    if (paramMap.containsKey("filterFields")) {
        reportParams.put("filterFields", paramMap.get("filterFields")[0]);
    }
    if (paramMap.containsKey("sortFields")) {
        reportParams.put("sortFields", paramMap.get("sortFields")[0]);
    }
    reportOutputFormat = systemProgram.getRptformat();
    String fileName = systemProgram.getApi() + BaseLib.formatDate("yyyyMMddHHmmss", BaseLib.getDate()) + "."
            + reportOutputFormat;
    String reportName = reportPath + systemProgram.getRptdesign();
    String outputName = reportOutputPath + fileName;
    reportViewPath = reportViewContext + fileName;
    try {
        if ("EFGP".equals(system)) {
            OutputStream os = new FileOutputStream(outputName);
            PdfCopyFields pdfCopy = new PdfCopyFields(os);
            ByteArrayOutputStream baos;
            //??
            this.setReportClass(Class.forName(systemProgram.getRptclazz()).getClassLoader());
            //??
            this.reportInitAndConfig();
            //?
            baos = new ByteArrayOutputStream();
            this.reportRunAndOutput(reportName, reportParams, null, "pdf", baos);
            pdfCopy.addDocument(new PdfReader(baos.toByteArray()));
            //???
            if ("HZ_CW028".equals(api)) {
                String formSerialNumber = hzcw028Bean.findByPSN(reportParams.get("formid"))
                        .getFormSerialNumber();
                if (hzcw028Bean.getTrafficDetail(formSerialNumber).size() > 0) {
                    baos = new ByteArrayOutputStream();
                    this.reportRunAndOutput(reportPath + "hzcw02802.rptdesign", reportParams, null, "pdf",
                            baos);
                    pdfCopy.addDocument(new PdfReader(baos.toByteArray()));
                }
            }

            //??
            this.setReportClass(Class.forName("cn.hanbell.efgp.rpt.ProcessCheckReport").getClassLoader());//??
            reportParams.remove("JNDIName");
            reportParams.put("JNDIName",
                    "java:global/Hanbell-EAP/EFGP-ejb/ProcessCheckBean!cn.hanbell.oa.ejb.ProcessCheckBean");//??Bean
            //??
            this.reportInitAndConfig();
            //?
            baos = new ByteArrayOutputStream();
            this.reportRunAndOutput(reportPath + "processcheck.rptdesign", reportParams, null, "pdf", baos);
            pdfCopy.addDocument(new PdfReader(baos.toByteArray()));
            //??
            pdfCopy.close();
        } else {
            this.setReportClass(Class.forName(systemProgram.getRptclazz()).getClassLoader());
            //??
            this.reportInitAndConfig();
            //?
            this.reportRunAndOutput(reportName, reportParams, outputName, reportOutputFormat, null);
        }
        //
        this.preview();
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:cn.hanbell.war.control.BillPrintManagedBean.java

public void print(String rptdesign) throws Exception {
    if (currentPrgGrant == null || entityList == null || entityList.isEmpty()) {
        return;//www  .j ava  2  s  . co m
    }
    String reportName, outputName, reportFormat;
    //??
    reportName = reportPath + currentPrgGrant.getSysprg().getRptdesign();
    //??
    fileName = "BillPrint" + BaseLib.formatDate("yyyyMMddHHmmss", getDate()) + ".pdf";
    outputName = reportOutputPath + fileName;
    OutputStream os = new FileOutputStream(outputName);
    if (this.currentPrgGrant != null && this.currentPrgGrant.getSysprg().getRptclazz() != null) {
        reportClassLoader = Class.forName(this.currentPrgGrant.getSysprg().getRptclazz()).getClassLoader();
    }
    PdfCopyFields pdfCopy = new PdfCopyFields(os);
    HashMap<String, Object> reportParams = new HashMap<>();
    ByteArrayOutputStream baos;
    for (Armbill c : entityList) {
        //?
        baos = new ByteArrayOutputStream();
        reportParams.put("company", userManagedBean.getCurrentCompany().getName());
        reportParams.put("companyFullName", userManagedBean.getCurrentCompany().getFullname());
        reportParams.put("tel", userManagedBean.getCurrentCompany().getTel());
        reportParams.put("fax", userManagedBean.getCurrentCompany().getFax());
        reportParams.put("id", c.getId());
        reportParams.put("formid", c.getFormid());
        reportParams.put("JNDIName", currentPrgGrant.getSysprg().getRptjndi());
        try {
            //??
            this.reportInitAndConfig();
            //?
            this.reportRunAndOutput(reportName, reportParams, null, "pdf", baos);
        } catch (Exception ex) {
            throw ex;
        } finally {
            reportParams.clear();
            c.setStatus("P");
            currentEntity = c;
            update();
        }
        pdfCopy.addDocument(new PdfReader(baos.toByteArray()));
    }
    pdfCopy.close();
    this.reportViewPath = reportViewContext + fileName;
    this.preview();
}

From source file:cn.hanbell.war.control.ShipmentPrintManagedBean.java

public void print(String rptdesign) throws Exception {
    if (currentPrgGrant == null || entityList == null || entityList.isEmpty()) {
        return;/*from   w w  w .  jav  a2s .  c o m*/
    }
    String reportName, outputName, reportFormat;
    //??
    //reportName = reportPath + currentPrgGrant.getSysprg().getRptdesign();
    //??
    fileName = "ShipmentPrint" + BaseLib.formatDate("yyyyMMddHHmmss", getDate()) + ".pdf";
    outputName = reportOutputPath + fileName;
    OutputStream os = new FileOutputStream(outputName);
    if (this.currentPrgGrant != null && this.currentPrgGrant.getSysprg().getRptclazz() != null) {
        reportClassLoader = Class.forName(this.currentPrgGrant.getSysprg().getRptclazz()).getClassLoader();
    }
    PdfCopyFields pdfCopy = new PdfCopyFields(os);
    HashMap<String, Object> reportParams = new HashMap<>();
    ByteArrayOutputStream baos;
    for (Shipment c : entityList) {
        //?
        baos = new ByteArrayOutputStream();
        reportParams.put("company", userManagedBean.getCurrentCompany().getName());
        reportParams.put("companyFullName", userManagedBean.getCurrentCompany().getFullname());
        reportParams.put("tel", userManagedBean.getCurrentCompany().getTel());
        reportParams.put("fax", userManagedBean.getCurrentCompany().getFax());
        reportParams.put("id", c.getId());
        reportParams.put("formid", c.getFormid());
        reportParams.put("JNDIName", currentPrgGrant.getSysprg().getRptjndi());
        try {
            //?????
            reportName = reportPath + c.getCustomerno() + rptdesign + ".rptdesign";
            //??
            this.reportInitAndConfig();
            //?
            this.reportRunAndOutput(reportName, reportParams, null, "pdf", baos);
        } catch (Exception ex) {
            throw ex;
        } finally {
            reportParams.clear();
            c.setStatus("P");
            currentEntity = c;
            update();
        }
        pdfCopy.addDocument(new PdfReader(baos.toByteArray()));
    }
    pdfCopy.close();
    this.reportViewPath = reportViewContext + fileName;
    this.preview();
}

From source file:cn.hanbell.war.control.WarrentyPrintManagedBean.java

public void print(String rptdesign) throws Exception {
    if (currentPrgGrant == null || entityList == null || entityList.isEmpty()) {
        return;/*from  w  w  w . j  a v a2  s .  c om*/
    }
    String reportName, outputName, reportFormat;
    //??
    //reportName = reportPath + currentPrgGrant.getSysprg().getRptdesign();
    //??
    fileName = "WarrentyPrint" + BaseLib.formatDate("yyyyMMddHHmmss", getDate()) + ".pdf";
    outputName = reportOutputPath + fileName;
    OutputStream os = new FileOutputStream(outputName);
    if (this.currentPrgGrant != null && this.currentPrgGrant.getSysprg().getRptclazz() != null) {
        reportClassLoader = Class.forName(this.currentPrgGrant.getSysprg().getRptclazz()).getClassLoader();
    }
    PdfCopyFields pdfCopy = new PdfCopyFields(os);
    HashMap<String, Object> reportParams = new HashMap<>();
    ByteArrayOutputStream baos;
    for (Shipment c : entityList) {
        //?
        baos = new ByteArrayOutputStream();
        reportParams.put("company", userManagedBean.getCurrentCompany().getName());
        reportParams.put("companyFullName", userManagedBean.getCurrentCompany().getFullname());
        reportParams.put("tel", userManagedBean.getCurrentCompany().getTel());
        reportParams.put("fax", userManagedBean.getCurrentCompany().getFax());
        reportParams.put("id", c.getId());
        reportParams.put("formid", c.getFormid());
        reportParams.put("JNDIName", currentPrgGrant.getSysprg().getRptjndi());
        try {
            reportName = reportPath + rptdesign + ".rptdesign";
            //??
            this.reportInitAndConfig();
            //?
            this.reportRunAndOutput(reportName, reportParams, null, "pdf", baos);
        } catch (Exception ex) {
            throw ex;
        } finally {
            reportParams.clear();
            c.setStatus("P");
            currentEntity = c;
            update();
        }
        pdfCopy.addDocument(new PdfReader(baos.toByteArray()));
    }
    pdfCopy.close();
    this.reportViewPath = reportViewContext + fileName;
    this.preview();
}

From source file:com.dgpx.control.ExamNumberManagedBean.java

@Override
public void print() throws Exception {

    if (currentEntity == null) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_WARN, "Warn", "???"));
        return;//  ww  w.  j  av  a2  s  .  c om
    }
    examNumberBean.setDetail(currentEntity.getId());
    if (examNumberBean.getDetailList().isEmpty()) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_WARN, "Warn", "???"));
        return;
    } else {
        for (ExamCard c : examNumberBean.getDetailList()) {
            if (!c.getStatus().equals("Z")) {
                c.setStatus("Z");
                examCardBean.update(c);
            }
        }
    }

    String reportName, outputName;
    //??
    reportName = reportPath + this.currentSysprg.getRptdesign();
    //??
    outputName = reportOutputPath + currentEntity.getFormid() + ".pdf";
    OutputStream os = new FileOutputStream(outputName);
    PdfCopyFields pdfCopy = new PdfCopyFields(os);
    HashMap<String, Object> params = new HashMap<>();
    ByteArrayOutputStream baos;
    for (ExamCard c : examNumberBean.getDetailList()) {
        //?
        baos = new ByteArrayOutputStream();
        params.put("id", c.getId());
        params.put("JNDIName", this.currentSysprg.getRptjndi());
        try {
            //??
            this.reportInitAndConfig();
            //?
            this.reportRunAndOutput(reportName, params, null, "pdf", baos);
        } catch (Exception ex) {
            throw ex;
        } finally {
            params.clear();
        }
        pdfCopy.addDocument(new PdfReader(baos.toByteArray()));
    }
    pdfCopy.close();
    this.reportViewPath = reportViewContext + currentEntity.getFormid() + ".pdf";
    this.preview();
}

From source file:com.krawler.spring.crm.common.sendemailnotification.java

License:Open Source License

public void exportPDF(String reportname, String userid, String username, String userEmailID,
        ByteArrayOutputStream byStage, ByteArrayOutputStream byRegion, ByteArrayOutputStream bySalesPerson,
        String partnerName, String sysEmailId) {
    try {/*from   ww w .  j  av a2  s .  c  om*/
        PdfReader reader = null;
        PdfReader reader2 = null;
        PdfReader reader3 = null;
        // new reader with the PDF just created
        if (byStage.size() > 0) {
            reader = new PdfReader(byStage.toByteArray());
        }
        // 2nd reader with pdf
        if (byRegion.size() > 0) {
            reader2 = new PdfReader(byRegion.toByteArray());
        }

        // 3rd reader with pdf
        if (bySalesPerson.size() > 0) {
            reader3 = new PdfReader(bySalesPerson.toByteArray());
        }

        PdfCopyFields copy = new PdfCopyFields(byStage);
        if (reader != null)
            copy.addDocument(reader);
        if (reader2 != null)
            copy.addDocument(reader2);
        if (reader3 != null)
            copy.addDocument(reader3);
        copy.close();

        //                response.setHeader("Content-Disposition", "attachment; filename=\"" + reportname + ".pdf\"");
        //                response.setContentType("application/octet-stream");
        //                response.setContentLength(byStage.size());
        //                response.getOutputStream().write(byStage.toByteArray());
        //                response.getOutputStream().flush();
        //                response.getOutputStream().close();

        if (byStage.size() > 0) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String GenerateDate = df.format(new Date());
            String fileName = reportname + "_" + userid + "_" + GenerateDate + ".pdf";
            String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "opportunityreport";
            java.io.File destDir = new java.io.File(destinationDirectory);
            if (!destDir.exists()) { //Create destination folder if not present
                destDir.mkdirs();
            }
            fileName = destinationDirectory + "/" + fileName;

            java.io.FileOutputStream fileOut = new java.io.FileOutputStream(fileName);
            fileOut.write(byStage.toByteArray());
            fileOut.flush();
            fileOut.close();

            String htmltxt = "Hi <b>" + username + "</b>,<br><br>";
            htmltxt += "<br/><br/>Attachment is the pdf file containing Opportunity sales report.";
            htmltxt += "<br/>For queries, email us at " + sysEmailId + "<br/>";
            htmltxt += "<br/>" + partnerName + " Admin";

            String plainMsg = "Hi " + username + " ,\n\n";
            plainMsg += "\n\nAttachment is the pdf file containing Opportunity sales report.";
            plainMsg += "\nFor queries, email us at " + sysEmailId + "\n";
            plainMsg += "\n" + partnerName + " Admin";
            if (!StringUtil.isNullOrEmpty(userEmailID)) {
                SendMailHandler.postMailAttachment(new String[] { userEmailID },
                        "[" + partnerName + " CRM] - Opportuniy sales reports.", htmltxt, plainMsg,
                        partnerName + " Admin<" + sysEmailId + ">", fileName, reportname + ".pdf");
            }
        }
    } catch (Exception e) {
        Logger.getLogger(sendemailnotification.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:com.nabla.wapp.report.server.ReportTemplateList.java

License:Apache License

public Report mergeToPdf(final Connection conn, final Map<String, Object> parameters, final Locale locale)
        throws InternalErrorException {
    final ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    try {//from www . j a v a 2  s . com
        final PdfCopyFields pdf = new PdfCopyFields(tmp);
        try {
            for (ReportTemplate template : this)
                pdf.addDocument(template.generatePdf(conn, parameters, locale));
        } finally {
            pdf.close();
        }
    } catch (DocumentException e) {
        throw new InternalErrorException(Util.formatInternalErrorDescription(e));
    } catch (IOException e) {
        throw new InternalErrorException(Util.formatInternalErrorDescription(e));
    }
    return new Report("name", new ByteArrayInputStream(tmp.toByteArray()), ReportFormats.PDF);
}

From source file:com.qubit.terra.docs.util.ReportGenerator.java

License:Open Source License

public static byte[] concatPDFs(Collection<byte[]> documents) {

    try {/*from w  w  w  .j  a va2 s  .co  m*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PdfCopyFields copy = new PdfCopyFields(outputStream);

        for (byte[] doc : documents) {
            copy.addDocument(new PdfReader(doc));
        }

        copy.close();

        return outputStream.toByteArray();
    } catch (DocumentException e) {
        throw new ReportGenerationException("Error in opening document", e);
    } catch (IOException e) {
        throw new ReportGenerationException("Error in opening document", e);
    }
}

From source file:com.stackframe.pdfliberator.PDFLiberator.java

License:GNU General Public License

/**
 * Removes the owner password on a PDF document passed through as a stream.
 *
 * @param input the InputStream containing the document to liberate
 * @param output the OutputStream to write the liberated document to
 * @throws IOException if there is a problem reading from or writing to the supplied streams
 * @throws DocumentException if there is a problem parsing or writing the PDF document
 */// www  .j a v a 2s  . c o m
public static void liberate(InputStream input, OutputStream output) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(input);
    try {
        setBooleanField(reader, "ownerPasswordUsed", false);
        setBooleanField(reader, "encrypted", false);
    } catch (NoSuchFieldException nsfe) {
        // We expect these fields to be part of iText.  If they are not found, then we are probably using a different version.
        AssertionError ae = new AssertionError("could not find a field");
        ae.initCause(nsfe);
        throw ae;
    }

    reader.removeUsageRights();
    PdfCopyFields copy = new PdfCopyFields(output);
    copy.addDocument(reader);
    copy.close();
}