Example usage for com.lowagie.text DocumentException DocumentException

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

Introduction

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

Prototype

public DocumentException(String message) 

Source Link

Document

Constructs a DocumentException with a message.

Usage

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.itext.PatchRtfWriter2.java

License:Open Source License

/**
 * Adds a fragment of an RTF document to the current RTF document being generated. Since this fragment doesn't contain
 * font or color tables, all fonts and colors are mapped to the default font and color. If the font and color mappings
 * are known, they can be specified via the mappings parameter. Uses new RtfParser object.
 * <p/>/*  ww w .j  av  a2s . c  o m*/
 * (author: Howard Shank)
 *
 * @param documentSource
 *          The InputStream to read the RTF fragment from.
 * @param mappings
 *          The RtfImportMappings that contain font and color mappings to apply to the fragment.
 * @param events
 *          The array of event listeners. May be null
 * @throws IOException
 *           On errors reading the RTF fragment.
 * @throws DocumentException
 *           On errors adding to this RTF fragment.
 * @see RtfImportMappings
 * @see RtfParser
 * @see RtfParser#importRtfFragment(InputStream, com.lowagie.text.rtf.document.RtfDocument, RtfImportMappings)
 * @since 2.0.8
 */
public void importRtfFragment(InputStream documentSource, RtfImportMappings mappings, EventListener[] events)
        throws IOException, DocumentException {
    if (!this.open) {
        throw new DocumentException("The document must be open to import RTF fragments.");
    }
    RtfParser rtfImport = new RtfParser(this.document);
    if (events != null) {
        for (int idx = 0; idx < events.length; idx++) {
            rtfImport.addListener(events[idx]);
        }
    }
    rtfImport.importRtfFragment(documentSource, this.rtfDoc, mappings);
}

From source file:org.pentaho.reporting.libraries.fonts.itext.BaseFontSupport.java

License:Open Source License

/**
 * Creates a PDF font record from a true type font.
 *
 * @param encoding       the encoding.//from  ww w . ja  va 2  s  . c  om
 * @param stringEncoding the string encoding.
 * @param embedded       a flag indicating whether to embed the font glyphs in the generated documents.
 * @return the PDF font record.
 * @throws com.lowagie.text.DocumentException if the BaseFont could not be created.
 */
private BaseFontRecord createFontFromTTF(final FontRecord fontRecord, final boolean bold, final boolean italic,
        final String encoding, final String stringEncoding, final boolean embedded) throws DocumentException {
    // check if this font is in the cache ...
    //Log.warn ("TrueTypeFontKey : " + fontKey + " Font: " + font.isItalic() + " Encoding: "
    //          + encoding);
    final String rawFilename;
    if (fontRecord instanceof TrueTypeFontRecord) {
        final TrueTypeFontRecord ttfRecord = (TrueTypeFontRecord) fontRecord;
        if (ttfRecord.getCollectionIndex() >= 0) {
            rawFilename = ttfRecord.getFontSource() + ',' + ttfRecord.getCollectionIndex();
        } else {
            rawFilename = ttfRecord.getFontSource();
        }
    } else if (fontRecord instanceof FontSource) {
        final FontSource source = (FontSource) fontRecord;
        rawFilename = source.getFontSource();
    } else {
        return null;
    }

    final String filename;
    // check, whether the the physical font does not provide some of the
    // required styles. We have to synthesize them, if neccessary
    if ((fontRecord.isBold() == false && bold) && (fontRecord.isItalic() == false && italic)) {
        filename = rawFilename + ",BoldItalic";
    } else if (fontRecord.isBold() == false && bold) {
        filename = rawFilename + ",Bold";
    } else if (fontRecord.isItalic() == false && italic) {
        filename = rawFilename + ",Italic";
    } else {
        filename = rawFilename;
    }

    final BaseFontRecord fontRec = getFromCache(filename, encoding, embedded);
    if (fontRec != null) {
        return fontRec;
    }

    BaseFont f;
    try {
        try {
            f = BaseFont.createFont(filename, encoding, embedded, false, null, null);
        } catch (DocumentException e) {
            f = BaseFont.createFont(filename, stringEncoding, embedded, false, null, null);
        }
    } catch (IOException ioe) {
        throw new DocumentException("Failed to read the font: " + ioe);
    }

    // no, we have to create a new instance
    final BaseFontRecord record = new BaseFontRecord(filename, true, embedded, f, fontRecord.isBold(),
            fontRecord.isItalic());
    putToCache(record);
    return record;
}

From source file:org.xhtmlrenderer.pdf.TrueTypeUtil.java

License:Open Source License

private static RandomAccessFileOrArray populateDescription0(String path, BaseFont font, FontDescription descr,
        RandomAccessFileOrArray rf)/* ww  w. j  av a2s. c om*/
        throws NoSuchFieldException, IllegalAccessException, DocumentException, IOException {
    Map tables = extractTables(font);

    descr.setStyle(guessStyle(font));

    int[] location = (int[]) tables.get("OS/2");
    if (location == null) {
        throw new DocumentException("Table 'OS/2' does not exist in " + path);
    }
    rf.seek(location[0]);
    int want = 4;
    long got = rf.skip(want);
    if (got < want) {
        throw new DocumentException("Skip TT font weight, expect read " + want + " bytes, but only got " + got);
    }
    descr.setWeight(rf.readUnsignedShort());
    want = 20;
    got = rf.skip(want);
    if (got < want) {
        throw new DocumentException(
                "Skip TT font strikeout, expect read " + want + " bytes, but only got " + got);
    }
    descr.setYStrikeoutSize(rf.readShort());
    descr.setYStrikeoutPosition(rf.readShort());

    location = (int[]) tables.get("post");

    if (location != null) {
        rf.seek(location[0]);
        want = 8;
        got = rf.skip(want);
        if (got < want) {
            throw new DocumentException(
                    "Skip TT font underline, expect read " + want + " bytes, but only got " + got);
        }
        descr.setUnderlinePosition(rf.readShort());
        descr.setUnderlineThickness(rf.readShort());
    }

    rf.close();
    rf = null;
    return rf;
}

From source file:oscar.eform.actions.FaxAction.java

License:Open Source License

/**
 * This method will take eforms and send them to a PHR.
 * @throws DocumentException /* w ww  .j a  v a  2s .  co m*/
 */
public void faxForms(String[] numbers, String formId, String providerId) throws DocumentException {

    File tempFile = null;

    try {
        logger.info("Generating PDF for eform with fdid = " + formId);

        tempFile = File.createTempFile("EForm." + formId, ".pdf");
        //tempFile.deleteOnExit();

        // convert to PDF
        String viewUri = localUri + formId;
        WKHtmlToPdfUtils.convertToPdf(viewUri, tempFile);
        logger.info("Writing pdf to : " + tempFile.getCanonicalPath());

        // Removing all non digit characters from fax numbers.
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = numbers[i].trim().replaceAll("\\D", "");
        }
        ArrayList<String> recipients = new ArrayList<String>(Arrays.asList(numbers));

        // Removing duplicate phone numbers.
        recipients = new ArrayList<String>(new HashSet<String>(recipients));
        String tempPath = System.getProperty("java.io.tmpdir");
        FileOutputStream fos;
        for (int i = 0; i < recipients.size(); i++) {
            String faxNo = recipients.get(i).trim().replaceAll("\\D", "");
            if (faxNo.length() < 7) {
                throw new DocumentException("Document target fax number '" + faxNo + "' is invalid.");
            }
            String tempName = "EForm-" + formId + "." + System.currentTimeMillis();

            String tempPdf = String.format("%s%s%s.pdf", tempPath, File.separator, tempName);
            String tempTxt = String.format("%s%s%s.txt", tempPath, File.separator, tempName);

            // Copying the fax pdf.
            FileUtils.copyFile(tempFile, new File(tempPdf));

            // Creating text file with the specialists fax number.
            fos = new FileOutputStream(tempTxt);
            PrintWriter pw = new PrintWriter(fos);
            pw.println(faxNo);
            pw.close();
            fos.close();

            // A little sanity check to ensure both files exist.
            if (!new File(tempPdf).exists() || !new File(tempTxt).exists()) {
                throw new DocumentException("Unable to create files for fax of eform " + formId + ".");
            }
            if (skipSave) {
                EFormDataDao eFormDataDao = (EFormDataDao) SpringUtils.getBean("EFormDataDao");
                EFormData eFormData = eFormDataDao.find(Integer.parseInt(formId));
                eFormData.setCurrent(false);
                eFormDataDao.merge(eFormData);
            }
        }
        // Removing the consulation pdf.
        tempFile.delete();

    } catch (IOException e) {
        MiscUtils.getLogger().error("Error converting and sending eform. id=" + formId, e);
    }
}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.EctConsultationFormFaxAction.java

License:Open Source License

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//  w w  w  .ja  v  a  2s .c  o  m

    String reqId = (String) request.getAttribute("reqId");
    String demoNo = request.getParameter("demographicNo");
    ArrayList<EDoc> docs = EDocUtil.listDocs(demoNo, reqId, EDocUtil.ATTACHED);
    //      String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    ArrayList<Object> alist = new ArrayList<Object>();
    byte[] buffer;
    ByteInputStream bis;
    ByteOutputStream bos;
    CommonLabResultData consultLabs = new CommonLabResultData();
    ArrayList<InputStream> streams = new ArrayList<InputStream>();

    ArrayList<LabResultData> labs = consultLabs.populateLabResultsData(demoNo, reqId,
            CommonLabResultData.ATTACHED);
    String error = "";
    Exception exception = null;
    try {

        bos = new ByteOutputStream();
        ConsultationPDFCreator cpdfc = new ConsultationPDFCreator(request, bos);
        cpdfc.printPdf();

        buffer = bos.getBytes();
        bis = new ByteInputStream(buffer, bos.getCount());
        bos.close();
        streams.add(bis);
        alist.add(bis);

        for (int i = 0; i < docs.size(); i++) {
            EDoc doc = docs.get(i);
            if (doc.isPrintable()) {
                if (doc.isImage()) {
                    bos = new ByteOutputStream();
                    //                  request.setAttribute("imagePath", path + doc.getFileName());
                    request.setAttribute("imagePath", EDocUtil.getDocumentPath(doc.getFileName()));
                    request.setAttribute("imageTitle", doc.getDescription());
                    ImagePDFCreator ipdfc = new ImagePDFCreator(request, bos);
                    ipdfc.printPdf();

                    buffer = bos.getBytes();
                    bis = new ByteInputStream(buffer, bos.getCount());
                    bos.close();
                    streams.add(bis);
                    alist.add(bis);

                } else if (doc.isPDF()) {
                    //                  alist.add(path + doc.getFileName());
                    alist.add(EDocUtil.getDocumentPath(doc.getFileName()));
                } else {
                    logger.error("EctConsultationFormRequestPrintAction: " + doc.getType()
                            + " is marked as printable but no means have been established to print it.");
                }
            }
        }

        // Iterating over requested labs.
        for (int i = 0; labs != null && i < labs.size(); i++) {
            // Storing the lab in PDF format inside a byte stream.
            bos = new ByteOutputStream();
            request.setAttribute("segmentID", labs.get(i).segmentID);
            LabPDFCreator lpdfc = new LabPDFCreator(request, bos);
            lpdfc.printPdf();

            // Transferring PDF to an input stream to be concatenated with
            // the rest of the documents.
            buffer = bos.getBytes();
            bis = new ByteInputStream(buffer, bos.getCount());
            bos.close();
            streams.add(bis);
            alist.add(bis);

        }

        if (alist.size() > 0) {

            String referralFax = request.getParameter("fax");

            // Retrieving additional fax recipients.
            String[] tmpRecipients = request.getParameterValues("faxRecipients");

            // Removing all non digit characters from fax numbers.
            for (int i = 0; tmpRecipients != null && i < tmpRecipients.length; i++) {
                tmpRecipients[i] = tmpRecipients[i].trim().replaceAll("\\D", "");
            }
            ArrayList<String> recipients = tmpRecipients == null ? new ArrayList<String>()
                    : new ArrayList<String>(Arrays.asList(tmpRecipients));

            // Including consultant fax number if appropriate.
            if (referralFax != null) {
                recipients.add(referralFax.trim().replaceAll("\\D", ""));
            }

            // Removing duplicate phone numbers.
            recipients = new ArrayList<String>(new HashSet<String>(recipients));

            // Writing consultation request to disk as a pdf.
            String tempPath = System.getProperty("java.io.tmpdir");
            String faxPdf = String.format("%s%s%s.pdf", tempPath, File.separator,
                    reqId + System.currentTimeMillis());
            FileOutputStream fos = new FileOutputStream(faxPdf);
            ConcatPDF.concat(alist, fos);
            fos.close();

            //check if default fax no.
            String currentUserFaxNo = "";

            String smartfaxSiteBind = OscarProperties.getInstance().getProperty("smartfax_site_bind");
            if (smartfaxSiteBind != null)
                smartfaxSiteBind = smartfaxSiteBind.trim();
            if (org.oscarehr.common.IsPropertiesOn.isMultisitesEnable() && smartfaxSiteBind != null
                    && smartfaxSiteBind.equalsIgnoreCase("true")) {
                //get site fax number
                String siteName = "";
                if (request.getParameter("siteName") != null)
                    siteName = request.getParameter("siteName").trim();
                SiteDao siteDao = (SiteDao) SpringUtils.getBean("siteDao");
                Site site = siteDao.getByLocation(siteName);
                if (site != null && site.getFax() != null && site.getFax().length() > 0) {
                    currentUserFaxNo = site.getFax();
                }
            } else {
                if (request.getSession().getAttribute("user") != null)
                    currentUserFaxNo = getUserFax(request.getSession().getAttribute("user").toString());
            }

            String defaultFaxModem = SmartFaxUtil.getDefaultFaxModem(currentUserFaxNo);

            for (int i = 0; i < recipients.size(); i++) {
                String faxNo = recipients.get(i).replaceAll("\\D", "");
                if (faxNo.length() < 7) {
                    throw new DocumentException("Document target fax number '" + faxNo + "' is invalid.");
                }
                String tempName = "CRF-" + reqId + "." + System.currentTimeMillis();

                String tempPdf = String.format("%s%s%s.pdf", tempPath, File.separator, tempName);
                String tempTxt = String.format("%s%s%s.txt", tempPath, File.separator, tempName);

                // Copying the fax pdf.
                FileUtils.copyFile(new File(faxPdf), new File(tempPdf));

                // Creating text file with the specialists fax number.
                fos = new FileOutputStream(tempTxt);
                PrintWriter pw = new PrintWriter(fos);
                pw.println(faxNo);
                if (defaultFaxModem != null && defaultFaxModem.length() > 0)
                    pw.println(defaultFaxModem);
                pw.close();
                fos.close();

                // A little sanity check to ensure both files exist.
                if (!new File(tempPdf).exists() || !new File(tempTxt).exists()) {
                    throw new DocumentException(
                            "Unable to create files for fax of consultation request " + reqId + ".");
                }
            }
            // Removing the consultation PDF.
            new File(faxPdf).delete();
            request.setAttribute("faxSuccessful", true);
            return mapping.findForward("success");
        }

    } catch (DocumentException de) {
        error = "DocumentException";
        exception = de;
    } catch (IOException ioe) {
        error = "IOException";
        exception = ioe;
    } finally {
        // Cleaning up InputStreams created for concatenation.
        for (InputStream is : streams) {
            try {
                is.close();
            } catch (IOException e) {
                error = "IOException";
            }
        }
    }
    if (!error.equals("")) {
        logger.error(error + " occured insided ConsultationPrintAction", exception);
        request.setAttribute("printError", new Boolean(true));
        return mapping.findForward("error");
    }
    return null;
}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.ImagePDFCreator.java

License:Open Source License

/**
 * Prints the consultation request.//w  ww.ja v a2s.  c o m
 * @throws IOException when an error with the output stream occurs
 * @throws DocumentException when an error in document construction occurs
 */
public void printPdf() throws IOException, DocumentException {

    Image image;
    try {
        image = Image.getInstance((String) request.getAttribute("imagePath"));
    } catch (Exception e) {
        logger.error("Unexpected error:", e);
        throw new DocumentException(e);
    }

    // Create the document we are going to write to
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, os);

    document.setPageSize(PageSize.LETTER);
    ResourceBundle.getBundle("oscarResources", request.getLocale())
            .getString("oscarEncounter.oscarConsultationRequest.consultationFormPrint.msgImage");
    document.addCreator("OSCAR");
    document.open();

    int type = image.getOriginalType();
    if (type == Image.ORIGINAL_TIFF) {
        // The following is composed of code from com.lowagie.tools.plugins.Tiff2Pdf modified to create the 
        // PDF in memory instead of on disk
        RandomAccessFileOrArray ra = new RandomAccessFileOrArray((String) request.getAttribute("imagePath"));
        int comps = TiffImage.getNumberOfPages(ra);
        boolean adjustSize = false;
        PdfContentByte cb = writer.getDirectContent();
        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);
            if (img != null) {
                if (adjustSize) {
                    document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
                    document.newPage();
                    img.setAbsolutePosition(0, 0);
                } else {
                    if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                        img.scaleToFit(500, 700);
                    }
                    img.setAbsolutePosition(20, 20);
                    document.newPage();
                    document.add(
                            new Paragraph((String) request.getAttribute("imageTitle") + " - page " + (c + 1)));
                }
                cb.addImage(img);

            }
        }
        ra.close();
    } else {
        PdfContentByte cb = writer.getDirectContent();
        if (image.getScaledWidth() > 500 || image.getScaledHeight() > 700) {
            image.scaleToFit(500, 700);
        }
        image.setAbsolutePosition(20, 20);
        cb.addImage(image);
    }
    document.close();
}