Example usage for com.itextpdf.text DocumentException DocumentException

List of usage examples for com.itextpdf.text DocumentException DocumentException

Introduction

In this page you can find the example usage for com.itextpdf.text DocumentException DocumentException.

Prototype

public DocumentException(String message) 

Source Link

Document

Constructs a DocumentException with a message.

Usage

From source file:be.mxs.common.util.pdf.general.chuk.GeneralPDFCreator.java

public ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, ServletContext application,
        boolean filterApplied, int partsOfTransactionToPrint) throws DocumentException {
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter docWriter = null;//  w w w.j a v a 2s  .  co  m
    this.req = req;
    this.application = application;
    sContextPath = req.getContextPath();

    try {
        docWriter = PdfWriter.getInstance(doc, baosPDF);

        //*** META TAGS ***********************************************************************
        doc.addProducer();
        doc.addAuthor(user.person.firstname + " " + user.person.lastname);
        doc.addCreationDate();
        doc.addCreator("OpenClinic Software for Hospital Management");
        doc.addTitle("Medical Record Data for " + patient.firstname + " " + patient.lastname);
        doc.addKeywords(patient.firstname + ", " + patient.lastname);
        doc.setPageSize(PageSize.A4);

        //*** FOOTER **************************************************************************
        PDFFooter footer = new PDFFooter("OpenClinic pdf engine (c)2007, Post-Factum bvba\n"
                + MedwanQuery.getInstance().getLabel("web.occup", "medwan.common.patientrecord", sPrintLanguage)
                + " " + patient.getID("immatnew") + " " + patient.firstname + " " + patient.lastname);
        docWriter.setPageEvent(footer);
        doc.open();

        //*** HEADER **************************************************************************
        printDocumentHeader(req);

        //*** TITLE ***************************************************************************
        String title = getTran("Web.Occup", "medwan.common.occupational-health-record").toUpperCase();

        // add date restriction to document title
        title += "\n(" + getTran("web", "printdate") + ": " + dateFormat.format(new Date()) + ")";
        /*
        if(dateFrom!=null && dateTo!=null){
        if(dateFrom.getTime() == dateTo.getTime()){
            title+= "\n("+getTran("web","on")+" "+dateFormat.format(dateTo)+")";
        }
        else{
            title+= "\n("+getTran("pdf","date.from")+" "+dateFormat.format(dateFrom)+" "+getTran("pdf","date.to")+" "+dateFormat.format(dateTo)+")";
        }
        }
        else if(dateFrom!=null){
        title+= "\n("+getTran("web","since")+" "+dateFormat.format(dateFrom)+")";
        }
        else if(dateTo!=null){
        title+= "\n("+getTran("pdf","date.to")+" "+dateFormat.format(dateTo)+")";
        }*/

        Paragraph par = new Paragraph(title, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        par.setAlignment(Paragraph.ALIGN_CENTER);
        doc.add(par);

        //*** OTHER DOCUMENT ELEMENTS *********************************************************
        printAdminHeader(patient);
        //printKeyData(sessionContainerWO);
        printMedication(sessionContainerWO);
        printActiveDiagnosis(sessionContainerWO);
        printWarnings(sessionContainerWO);
        doc.add(new Paragraph(" "));

        //*** VACCINATION CARD ****************************************************************
        new be.mxs.common.util.pdf.general.oc.examinations.PDFVaccinationCard().printCard(doc,
                sessionContainerWO, transactionVO, patient, req, sProject, sPrintLanguage,
                new Integer(partsOfTransactionToPrint));

        //*** TRANSACTIONS ********************************************************************
        Enumeration e = req.getParameterNames();
        String paramName, paramValue, sTranID, sServerID;
        boolean transactionIDsSpecified = false;

        while (e.hasMoreElements()) {
            paramName = (String) e.nextElement();

            // transactionIDs were specified as request-parameters
            if (paramName.startsWith("tranAndServerID_")) {
                transactionIDsSpecified = true;

                paramValue = checkString(req.getParameter(paramName));
                sTranID = paramValue.substring(0, paramValue.indexOf("_"));
                sServerID = paramValue.substring(paramValue.indexOf("_") + 1);

                this.transactionVO = MedwanQuery.getInstance().loadTransaction(Integer.parseInt(sServerID),
                        Integer.parseInt(sTranID));
                loadTransaction(transactionVO, 2); // 2 = print whole transaction
            }
        }

        if (!transactionIDsSpecified) {
            printTransactions(filterApplied, partsOfTransactionToPrint);
        }
        doc.add(new Paragraph(" "));
        printSignature();
    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (doc != null)
            doc.close();
        if (docWriter != null)
            docWriter.close();
    }

    if (baosPDF.size() < 1) {
        throw new DocumentException("document has " + baosPDF.size() + " bytes");
    }

    return baosPDF;
}

From source file:be.mxs.common.util.pdf.general.dossierCreators.StaffDossierPDFCreator.java

public ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, ServletContext application)
        throws DocumentException {
    this.req = req;
    this.application = application;
    this.baosPDF = new ByteArrayOutputStream();

    String sURL = req.getRequestURL().toString();
    if (sURL.indexOf("openclinic", 10) > 0) {
        sURL = sURL.substring(0, sURL.indexOf("openclinic", 10));
    }//from  www.java 2 s  .com
    if (sURL.indexOf("openinsurance", 10) > 0) {
        sURL = sURL.substring(0, sURL.indexOf("openinsurance", 10));
    }

    String sContextPath = req.getContextPath() + "/";
    HttpSession session = req.getSession();
    String sProjectDir = (String) session.getAttribute("activeProjectDir");

    // if request from Chuk, project = chuk
    if (sContextPath.indexOf("chuk") > -1) {
        sContextPath = "openclinic/";
        sProjectDir = "projects/chuk/";
    }

    this.url = sURL;
    this.contextPath = sContextPath;
    this.projectDir = sProjectDir;

    try {
        docWriter = PdfWriter.getInstance(doc, baosPDF);

        //*** META TAGS ***********************************************************************
        doc.addProducer();
        doc.addAuthor(user.person.firstname + " " + user.person.lastname);
        doc.addCreationDate();
        doc.addCreator("OpenClinic Software for Hospital Management");
        doc.addTitle("Medical Record Data for " + patient.firstname + " " + patient.lastname);
        doc.addKeywords(patient.firstname + ", " + patient.lastname);
        doc.setPageSize(PageSize.A4);
        doc.open();

        //*** HEADER **************************************************************************
        printDocumentHeader(req);

        //*** TITLE ***************************************************************************
        String sTitle = getTran("web", "staffDossier").toUpperCase();
        printDocumentTitle(req, sTitle);

        //*** SECTIONS ************************************************************************
        /*
        - 1 : Administratie persoonlijk
        - 2 : Administratie priv
        - 3 : Human resources contracten
        - 4 : Human resources Competenties
        - 5 : Human resources carrire
        - 6 : Human resources disciplinair dossier
        - 7 : Human resources verlof en afwezigheden
        - 8 : Human resources salaris
        - 9 : Human resources uurrooster
        */
        boolean[] sections = new boolean[17];

        // which sections are chosen ?
        Enumeration parameters = req.getParameterNames();
        Vector paramNames = new Vector();
        String sParamName, sParamValue;

        // sort the parameternames
        while (parameters.hasMoreElements()) {
            sParamName = (String) parameters.nextElement();

            if (sParamName.startsWith("section_")) {
                paramNames.add(new Integer(sParamName.substring("section_".length())));
            }
        }
        Collections.sort(paramNames); // on number

        int sectionIdx = 0;
        for (int i = 0; i < paramNames.size(); i++) {
            sectionIdx = ((Integer) paramNames.get(i)).intValue() - 1;
            sections[sectionIdx] = checkString(req.getParameter("section_" + (sectionIdx + 1)))
                    .equalsIgnoreCase("on");
            Debug.println("Adding section[" + sectionIdx + "] to document : " + sections[sectionIdx]);
        }

        sectionIdx = 0;
        if (sections[sectionIdx++]) {
            printPatientCard(patient, sections[1]); // 0, showPhoto
            printAdminData(patient);
        }
        if (sections[sectionIdx++]) {
            //printPhoto(patient); // 1
        }
        if (sections[sectionIdx++]) {
            printAdminPrivateData(patient); // 2
        }
        if (sections[sectionIdx++]) {
            printHRContracts(sessionContainerWO, patient); // 3
        }
        if (sections[sectionIdx++]) {
            printHRSkills(sessionContainerWO, patient); // 4
        }
        if (sections[sectionIdx++]) {
            printHRCareer(sessionContainerWO, patient); // 5
        }
        if (sections[sectionIdx++]) {
            printHRDisciplinaryRecord(sessionContainerWO, patient); // 6
        }
        if (sections[sectionIdx++]) {
            printHRLeaves(sessionContainerWO, patient); // 8
        }
        if (sections[sectionIdx++]) {
            printHRSalary(sessionContainerWO, patient); // 9
        }
        if (sections[sectionIdx++]) {
            printHRWorkSchedules(sessionContainerWO, patient); // 10
        }
        if (sections[sectionIdx++]) {
            printHRTraining(sessionContainerWO, patient); // 11
        }
        if (sections[sectionIdx++]) {
            printSignature(); // 12 : not in jsp
        }
    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (doc != null)
            doc.close();
        if (docWriter != null)
            docWriter.close();
    }

    if (baosPDF.size() < 1) {
        throw new DocumentException("ERROR : The pdf-document has " + baosPDF.size() + " bytes");
    }

    return baosPDF;
}

From source file:com.vectorprint.report.itext.VectorPrintDocument.java

License:Open Source License

/**
 *
 * @param image/*  w w w  .j  av a  2 s. c o m*/
 * @param hook
 * @param prefix
 * @param wrap
 * @return true when the image was added to the document
 * @throws DocumentException
 */
private boolean tracePosition(Image image, AddElementHook hook, String prefix, boolean wrap)
        throws DocumentException {
    String gt = prefix + hook.styleClass;
    if (wrap && image.hasAbsoluteX() && image.hasAbsoluteY()) {
        // tracing position when an image is absolutely positioned by wrapping it in a chunk
        Chunk wrapper = new Chunk(image, (Float.NaN == image.getAbsoluteX()) ? 0 : image.getAbsoluteX(),
                (Float.NaN == image.getAbsoluteY()) ? 0 : image.getAbsoluteY(), true);
        try {
            styleHelper.delayedStyle(wrapper, gt,
                    StyleHelper.getStylers(factory.getStylers(gt.replaceFirst(prefix, "")), Advanced.class),
                    eventHelper);
        } catch (VectorPrintException ex) {
            throw new DocumentException(ex);
        }
        return super.add(wrapper);
    } else {
        // the chunk will provide feedback on the actual x and y of the image when onGenericTag is fired,
        // the width and height of the image are passed to the eventhelper
        Chunk chunk = positionChunk();
        try {
            styleHelper.delayedStyle(chunk, gt,
                    StyleHelper.getStylers(factory.getStylers(gt.replaceFirst(prefix, "")), Advanced.class),
                    eventHelper, image);
        } catch (VectorPrintException ex) {
            throw new DocumentException(ex);
        }
        super.add(chunk);
        return false;
    }
}

From source file:de.jost_net.JVerein.io.FormularfelderExportCSV.java

License:Open Source License

@Override
protected void open() throws DocumentException {
    formularfelder = new ArrayList<Formularfeld>();
    try {/*from www  .  ja v a 2  s  .  com*/
        writer = new CsvMapWriter(new FileWriter(file), CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);
        header = new String[] { "Name", "Seite", "X", "Y", "Font", "Fontsize", "Fontstyle" };
        writer.writeHeader(header);
    } catch (IOException e) {
        throw new DocumentException(e);
    }
}

From source file:de.jost_net.JVerein.io.StatistikJahrgaengeExportCSV.java

License:Open Source License

@Override
protected void open() throws DocumentException {
    try {/*from  w w  w  . j a v a 2 s  .c  o  m*/

        ICsvMapWriter writer = new CsvMapWriter(new FileWriter(file),
                CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);

        String[] header = new String[] { "Jahrgang", "m", "w", "o" };
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("Jahrgang", 2000);
        map.put("m", 1);
        map.put("w", 1);
        map.put("o", 1);
        CellProcessor[] processors = CellProcessors.createCellProcessors(map);

        writer.writeHeader(header);

        for (String key : statistik.keySet()) {
            StatistikJahrgang dsbj = statistik.get(key);
            map.put("Jahrgang", key);
            map.put("m", dsbj.getAnzahlmaennlich());
            map.put("w", dsbj.getAnzahlweiblich());
            map.put("o", dsbj.getAnzahlOhne());
            writer.write(map, header, processors);
        }
        GUI.getStatusBar().setSuccessText("Auswertung fertig.");
        writer.close();
        FileViewer.show(file);
    } catch (IOException e) {
        throw new DocumentException(e);
    }
}

From source file:de.rub.dez6a3.jpdfsigner.control.ITextSigner.java

License:Open Source License

public ByteArrayOutputStream doSign(byte[] pdf, Rectangle stampPos, int pageNmbrForStamp) throws IOException,
        DocumentException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Certificate[] chain = signCert.toArray(new Certificate[0]);

    PdfReader reader = new PdfReader(pdf);
    ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
    PdfStamper stp = PdfStamper.createSignature(reader, byteOS, '\0', null, true);
    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    if (stampPos != null) {
        sap.setVisibleSignature(/*from   www.j  a  v  a  2s.  co  m*/
                new com.itextpdf.text.Rectangle(stampPos.x, stampPos.y, stampPos.width, stampPos.height),
                pageNmbrForStamp, null);
        sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
        sap.setAcro6Layers(true);
    }
    //        Siganture Appearance

    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
    log.info("Creating signature with reason: " + ParamValidator.getInstance().getSignatureReason());
    sap.setReason(ParamValidator.getInstance().getSignatureReason());
    sap.setLocation("Ruhr-Universitt Bochum");
    Image i = Image.getInstance(getClass().getResource("/de/rub/dez6a3/jpdfsigner/resources/images/sign.png"));
    sap.setImage(i);
    sap.setCrypto((PrivateKey) signPrivKey, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
    dic.setReason(ParamValidator.getInstance().getSignatureReason());
    dic.setLocation("Ruhr-Universitt Bochum");
    sap.setCryptoDictionary(dic);
    // preserve some space for the contents
    int contentEstimated = 15000;
    HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
    sap.preClose(exc);
    // make the digest
    InputStream data = sap.getRangeStream();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte buf[] = new byte[8192];
    int n;
    while ((n = data.read(buf)) > 0) {
        messageDigest.update(buf, 0, n);
    }
    byte hash[] = messageDigest.digest();
    Calendar cal = Calendar.getInstance();
    // If we add a time stamp:
    TSAClient tsc = new TSAClientBouncyCastle("http://zeitstempel.dfn.de/");
    // Create the signature

    PdfPKCS7 sgn;
    try {
        sgn = new PdfPKCS7((PrivateKey) signPrivKey, chain, null, "SHA1", null, false);
        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null);
        sgn.update(sh, 0, sh.length);
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, null);

        if (contentEstimated + 2 < encodedSig.length) {
            throw new DocumentException("Not enough space");
        }

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
        // Replace the contents
        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        sap.close(dic2);
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
    }
    return byteOS;
}

From source file:es.sm2.openppm.front.utils.DocumentUtils.java

License:Open Source License

/**
 * Create PDF for Control Change/*from   www .  j  av a  2 s. c  o  m*/
 * @param idioma
 * @param project
 * @param change
 * @param preparedBy
 * @return
 * @throws DocumentException
 * @throws LogicException
 */
public static byte[] toPdf(ResourceBundle idioma, Project project, Changecontrol change, Employee preparedBy,
        final Image headerImg, final Image footerImg) throws DocumentException, LogicException {

    if (change == null) {
        throw new DocumentException("No change control found.");
    }

    if (preparedBy == null || preparedBy.getContact() == null) {
        throw new UserSendingException();
    }

    Document document = new Document(PageSize.A4);
    document.setMargins(70F, 70F, 38F, 38F); // Total Height: 842pt, Total Width: 595pt
    byte[] file = null;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    @SuppressWarnings("unused")
    PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);

    document.open();

    Font fontHeader = new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD);
    Font fontCell = new Font(FontFamily.TIMES_ROMAN, 9);
    Font tituloFont = new Font(FontFamily.TIMES_ROMAN, 16, Font.BOLD);

    document.add(new Paragraph(" ", tituloFont));
    document.add(new Paragraph(" ", tituloFont));
    document.add(new Paragraph(" ", fontHeader));
    Paragraph title = new Paragraph(idioma.getString("change_request").toUpperCase(), tituloFont);
    title.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(title);

    // Header Table
    // Project info
    PdfPTable tableHeader = new PdfPTable(3);
    tableHeader.setWidthPercentage(100);
    tableHeader.setSpacingBefore(10);
    tableHeader.setSpacingAfter(15);

    int[] colWidth = new int[3];
    colWidth[0] = 40;
    colWidth[1] = 30;
    colWidth[2] = 30;
    tableHeader.setWidths(colWidth);

    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.project_name"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.prepared_by"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(prepareHeaderCell(idioma.getString("change_request.date"), fontHeader, 1F, 1F, 0F, 1F));

    tableHeader.addCell(prepareCell(project.getProjectName() + " / " + project.getAccountingCode(), fontCell,
            0F, 0F, 0F, 1F));
    tableHeader.addCell(prepareCell(preparedBy.getContact().getFullName(), fontCell, 0F, 0F, 0F, 1F));
    tableHeader.addCell(prepareCell(DateUtil.format(idioma, new Date()), fontCell, 0F, 1F, 0F, 1F));

    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.customer"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.contact_name"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.customer_type"), fontHeader, 1F, 1F, 0F, 1F));

    tableHeader.addCell(prepareCell(project.getCustomer() != null ? project.getCustomer().getName() : "",
            fontCell, 0F, 0F, 0F, 1F));
    tableHeader.addCell(prepareCell((project.getCustomer() != null ? project.getCustomer().getName() : "-"),
            fontCell, 0F, 0F, 0F, 1F));

    Customertype cusType = (project.getCustomer() != null ? project.getCustomer().getCustomertype() : null);
    tableHeader.addCell(prepareCell(cusType == null ? "" : cusType.getName(), fontCell, 0F, 1F, 0F, 1F));

    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.business_manager"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.project_manager"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.originator"), fontHeader, 1F, 1F, 0F, 1F));

    Employee bm = project.getEmployeeByFunctionalManager();
    Employee pm = project.getEmployeeByProjectManager();

    tableHeader.addCell(prepareCell(bm == null ? "" : bm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F));
    tableHeader.addCell(prepareCell(pm == null ? "" : pm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F));
    tableHeader.addCell(prepareCell(change.getOriginator(), fontCell, 0F, 1F, 1F, 1F));

    document.add(tableHeader);

    // Change Information
    document.add(new Paragraph(idioma.getString("change_information")));

    PdfPTable tableInfo = new PdfPTable(1);
    tableInfo.setWidthPercentage(100);
    tableInfo.setSpacingBefore(10);
    tableInfo.setSpacingAfter(15);

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.change_type"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getChangetype().getDescription(), fontCell, 0F, 1F, 0F, 1F));

    String priorityDesc = "";
    if (change.getPriority().equals('H'))
        priorityDesc = idioma.getString("change.priority.high");
    if (change.getPriority().equals('N'))
        priorityDesc = idioma.getString("change.priority.normal");
    if (change.getPriority().equals('L'))
        priorityDesc = idioma.getString("change.priority.low");

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.priority"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(priorityDesc, fontCell, 0F, 1F, 0F, 1F));

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.desc"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getDescription(), fontCell, 0F, 1F, 0F, 1F));

    tableInfo.addCell(
            prepareHeaderCell(idioma.getString("change.recommended_solution"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getRecommendedSolution(), fontCell, 0F, 1F, 1F, 1F));

    PdfPTable tableSubInfo = new PdfPTable(3);
    tableSubInfo.setWidthPercentage(100);

    //TODO MIGRACION
    tableSubInfo.addCell(prepareSubCell(idioma.getString("change.wbs_node"), fontHeader));
    tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_effort"), fontHeader));
    tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_cost"), fontHeader));

    tableSubInfo.addCell(
            prepareSubCell((change.getWbsnode() != null ? change.getWbsnode().getName() : ""), fontCell));
    tableSubInfo.addCell(prepareSubCell(
            (change.getEstimatedEffort() != null ? String.valueOf(change.getEstimatedEffort()) : ""),
            fontCell));
    tableSubInfo.addCell(prepareSubCell(
            (change.getEstimatedCost() != null ? ValidateUtil.toCurrency(change.getEstimatedCost()) : ""),
            fontCell));

    PdfPCell subTable = new PdfPCell(tableSubInfo);
    subTable.setBorderWidth(1F);

    tableInfo.addCell(subTable);

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.impact_desc"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getImpactDescription(), fontCell, 0F, 1F, 1F, 1F));

    document.add(tableInfo);

    document.add(new Paragraph(idioma.getString("change.resolution")));

    PdfPTable tableResolution = new PdfPTable(1);
    tableResolution.setWidthPercentage(100);
    tableResolution.setSpacingBefore(10);
    tableResolution.setSpacingAfter(15);

    tableResolution
            .addCell(prepareHeaderCell(idioma.getString("change.resolution"), fontHeader, 1F, 1F, 0F, 1F));
    tableResolution.addCell(
            prepareCell((change.getResolution() != null && change.getResolution() ? idioma.getString("yes")
                    : idioma.getString("no")), fontCell, 0F, 1F, 0F, 1F));

    tableResolution
            .addCell(prepareHeaderCell(idioma.getString("change.resolution_date"), fontHeader, 1F, 1F, 0F, 1F));
    tableResolution.addCell(
            prepareCell(DateUtil.format(idioma, change.getResolutionDate()), fontCell, 0F, 1F, 0F, 1F));

    tableResolution.addCell(
            prepareHeaderCell(idioma.getString("change.resolution_reason"), fontHeader, 1F, 1F, 0F, 1F));
    tableResolution.addCell(prepareCell(change.getResolutionReason(), fontCell, 0F, 1F, 1F, 1F));

    document.add(tableResolution);

    document.close();

    try {

        PdfReader reader = new PdfReader(outputStream.toByteArray());
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        int numPag = reader.getNumberOfPages();

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            setHeaderFooter(i, numPag, headerImg, footerImg, reader, stamper, idioma);
        }

        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    file = outputStream.toByteArray();

    return file;
}

From source file:Model.MyPdfDocument.java

License:Open Source License

/**
 * Write the pdf file//from  w w w .jav  a  2  s.  c  om
 * Escreve o arquivo pdf
 */
private void write(ArrayList<ArrayList<String>> stList, String filename)
        throws DocumentException, FileNotFoundException, UnsupportedEncodingException {
    Document document = null;

    try {
        document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();

        MyFontSelector myFontSelector = MyFontSelector.getInstance();
        FontSelector fontSelector;
        Phrase phrase;

        for (ArrayList<String> stL : stList) {

            fontSelector = myFontSelector.getFontSelector("TITLE");
            phrase = fontSelector.process(stL.remove(0));
            document.add(new Paragraph(phrase));

            Paragraph paragraph = new Paragraph();
            addEmptyLine(paragraph, 1);

            for (String st : stL) {
                fontSelector = myFontSelector.getFontSelector(getFontString(st));

                /**
                 * In Windows we have some problems with Latin characters
                 * and we need to forces the encoding to UFT8
                 * 
                 * No Windows tivemos alguns problemas com caracteres latinos
                 * e foi necessrio forar a codificao para UTF8
                 */
                if (isWindows()) {
                    st = new String(st.getBytes(), "UTF8");
                }

                st = replace(st);

                phrase = fontSelector.process(st);
                paragraph.add(phrase);
            }

            document.add(paragraph);
            document.newPage();
        }

    } catch (DocumentException ex) {
        throw new DocumentException("Read error");
    } catch (FileNotFoundException ex) {
        throw new FileNotFoundException("File [" + filename + "] not found");
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:qedit.export.PDFObject.java

License:GNU General Public License

public void publish(OutputStream stream) throws Exception {
    if (stream == null) {
        throw new NullPointerException("Cannot public pdf to a null output stream");
    }//  w  ww .j  a  v a2 s . c om
    try {
        /*
         * Initialize the document...
         */
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, stream);
        } catch (ClassCastException ex) {
            throw new ClassCastException("The stream you provided is not a valid output stream");
        }
        doc.open();
        /*
         * Meta-information about the document...
         */
        doc.addAuthor(pdfAuthor);
        doc.addCreationDate();
        doc.addProducer();
        doc.addSubject(subject);
        doc.addCreator(pdfCreator);
        doc.addTitle(pdfTitle);
        doc.addKeywords(pdfKeywords);
        doc.addHeader("License", "GNU GPL v3");
        doc.add(new Paragraph("\n\n\n"));
        for (Element e : elements) {
            doc.add(e);
        }
        doc.close();
    } catch (DocumentException ex) {
        throw new DocumentException("Error while generating PDF representation.");
    }

}