Search in sources :

Example 21 with Document

use of com.lowagie.text.Document in project mdw-designer by CenturyLinkCloud.

the class ExportHelper method printImagePdf.

public void printImagePdf(String filename, DesignerCanvas canvas, Dimension graphsize) {
    try {
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\winnt\\fonts");
        // we create a template and a Graphics2D object that corresponds
        // with it
        // 1 inch
        int margin = 72;
        float scale = 0.5f;
        Rectangle pageSize;
        pageSize = PageSize.LETTER.rotate();
        Document document = new Document(pageSize);
        DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.setPageSize(pageSize);
        int imageW = (int) pageSize.getWidth() - margin;
        int imageH = (int) pageSize.getHeight() - margin;
        boolean edsave = canvas.editable;
        canvas.editable = false;
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        int horizontalPages = (int) (graphsize.width * scale) / imageW + 1;
        int verticalPages = (int) (graphsize.height * scale) / imageH + 1;
        for (int i = 0; i < horizontalPages; i++) {
            for (int j = 0; j < verticalPages; j++) {
                Image img;
                PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
                PdfTemplate tp = cb.createTemplate(imageW, imageH);
                Graphics2D g2 = tp.createGraphics(imageW, imageH, mapper);
                tp.setWidth(imageW);
                tp.setHeight(imageH);
                g2.scale(scale, scale);
                g2.translate(-i * imageW / scale, -j * imageH / scale);
                canvas.paintComponent(g2);
                g2.dispose();
                img = new ImgTemplate(tp);
                document.add(img);
            }
        }
        canvas.setBackground(bgsave);
        canvas.editable = edsave;
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) ImgTemplate(com.lowagie.text.ImgTemplate) Color(java.awt.Color) Rectangle(com.lowagie.text.Rectangle) DefaultFontMapper(com.lowagie.text.pdf.DefaultFontMapper) HTMLDocument(javax.swing.text.html.HTMLDocument) Document(com.lowagie.text.Document) BufferedImage(java.awt.image.BufferedImage) Image(com.lowagie.text.Image) DocWriter(com.lowagie.text.DocWriter) PdfTemplate(com.lowagie.text.pdf.PdfTemplate) BadLocationException(javax.swing.text.BadLocationException) BadElementException(com.lowagie.text.BadElementException) IOException(java.io.IOException) Graphics2D(java.awt.Graphics2D) FileOutputStream(java.io.FileOutputStream) PdfContentByte(com.lowagie.text.pdf.PdfContentByte)

Example 22 with Document

use of com.lowagie.text.Document in project ofbiz-framework by apache.

the class PdfSurveyServices method buildPdfFromSurveyResponse.

/**
 */
public static Map<String, Object> buildPdfFromSurveyResponse(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
    Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
    Delegator delegator = dctx.getDelegator();
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String surveyResponseId = (String) context.get("surveyResponseId");
    String contentId = (String) context.get("contentId");
    String surveyId = null;
    Document document = new Document();
    try {
        if (UtilValidate.isNotEmpty(surveyResponseId)) {
            GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
            if (surveyResponse != null) {
                surveyId = surveyResponse.getString("surveyId");
            }
        }
        if (UtilValidate.isNotEmpty(surveyId) && UtilValidate.isEmpty(contentId)) {
            GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
            if (survey != null) {
                String acroFormContentId = survey.getString("acroFormContentId");
                if (UtilValidate.isNotEmpty(acroFormContentId)) {
                    context.put("contentId", acroFormContentId);
                }
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        List<GenericValue> responses = EntityQuery.use(delegator).from("SurveyResponseAnswer").where("surveyResponseId", surveyResponseId).queryList();
        for (GenericValue surveyResponseAnswer : responses) {
            String value = null;
            String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
            GenericValue surveyQuestion = EntityQuery.use(delegator).from("SurveyQuestion").where("surveyQuestionId", surveyQuestionId).queryOne();
            String questionType = surveyQuestion.getString("surveyQuestionTypeId");
            // DEJ20060227 this isn't used, if needed in the future should get from SurveyQuestionAppl.externalFieldRef String fieldName = surveyQuestion.getString("description");
            if ("OPTION".equals(questionType)) {
                value = surveyResponseAnswer.getString("surveyOptionSeqId");
            } else if ("BOOLEAN".equals(questionType)) {
                value = surveyResponseAnswer.getString("booleanResponse");
            } else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType) || "NUMBER_FLOAT".equals(questionType)) {
                Double num = surveyResponseAnswer.getDouble("numericResponse");
                if (num != null) {
                    value = num.toString();
                }
            } else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
            // not really a question; ingore completely
            } else {
                value = surveyResponseAnswer.getString("textResponse");
            }
            Chunk chunk = new Chunk(surveyQuestion.getString("question") + ": " + value);
            Paragraph p = new Paragraph(chunk);
            document.add(p);
        }
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
        results.put("outByteBuffer", outByteBuffer);
    } catch (GenericEntityException | DocumentException e) {
        Debug.logError(e, module);
        results = ServiceUtil.returnError(e.getMessage());
    }
    return results;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.lowagie.text.Document) Chunk(com.lowagie.text.Chunk) ByteBuffer(java.nio.ByteBuffer) Paragraph(com.lowagie.text.Paragraph) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) DocumentException(com.lowagie.text.DocumentException) PdfObject(com.lowagie.text.pdf.PdfObject)

Example 23 with Document

use of com.lowagie.text.Document in project ofbiz-framework by apache.

the class CompDocServices method renderContentPdf.

public static Map<String, Object> renderContentPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String dataResourceId = null;
    Locale locale = (Locale) context.get("locale");
    String rootDir = (String) context.get("rootDir");
    String webSiteId = (String) context.get("webSiteId");
    String https = (String) context.get("https");
    Delegator delegator = dctx.getDelegator();
    String contentId = (String) context.get("contentId");
    String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
    try {
        Document document = new Document();
        document.setPageSize(PageSize.LETTER);
        document.open();
        GenericValue dataResource = null;
        if (UtilValidate.isEmpty(contentRevisionSeqId)) {
            GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
            dataResourceId = content.getString("dataResourceId");
            Debug.logInfo("SCVH(0b)- dataResourceId:" + dataResourceId, module);
            dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
        } else {
            GenericValue contentRevisionItem = EntityQuery.use(delegator).from("ContentRevisionItem").where("contentId", contentId, "itemContentId", contentId, "contentRevisionSeqId", contentRevisionSeqId).cache().queryOne();
            if (contentRevisionItem == null) {
                throw new ViewHandlerException("ContentRevisionItem record not found for contentId=" + contentId + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId);
            }
            Debug.logInfo("SCVH(1)- contentRevisionItem:" + contentRevisionItem, module);
            Debug.logInfo("SCVH(2)-contentId=" + contentId + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId, module);
            dataResourceId = contentRevisionItem.getString("newDataResourceId");
            Debug.logInfo("SCVH(3)- dataResourceId:" + dataResourceId, module);
            dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
        }
        String inputMimeType = null;
        if (dataResource != null) {
            inputMimeType = dataResource.getString("mimeTypeId");
        }
        byte[] inputByteArray = null;
        if (inputMimeType != null && "application/pdf".equals(inputMimeType)) {
            ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
            inputByteArray = byteBuffer.array();
        } else if (inputMimeType != null && "text/html".equals(inputMimeType)) {
            ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
            inputByteArray = byteBuffer.array();
            String s = new String(inputByteArray, "UTF-8");
            Debug.logInfo("text/html string:" + s, module);
        } else if (inputMimeType != null && "application/vnd.ofbiz.survey.response".equals(inputMimeType)) {
            String surveyResponseId = dataResource.getString("relatedDetailId");
            String surveyId = null;
            String acroFormContentId = null;
            GenericValue surveyResponse = null;
            if (UtilValidate.isNotEmpty(surveyResponseId)) {
                surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
                if (surveyResponse != null) {
                    surveyId = surveyResponse.getString("surveyId");
                }
            }
            if (UtilValidate.isNotEmpty(surveyId)) {
                GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
                if (survey != null) {
                    acroFormContentId = survey.getString("acroFormContentId");
                    if (UtilValidate.isNotEmpty(acroFormContentId)) {
                    // TODO: is something supposed to be done here?
                    }
                }
            }
            if (surveyResponse != null) {
                if (UtilValidate.isEmpty(acroFormContentId)) {
                    // Create AcroForm PDF
                    Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
                    if (ServiceUtil.isError(survey2PdfResults)) {
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
                    }
                    ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
                    inputByteArray = outByteBuffer.array();
                } else {
                    // Fill in acroForm
                    Map<String, Object> survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
                    if (ServiceUtil.isError(survey2AcroFieldResults)) {
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults);
                    }
                    ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
                    inputByteArray = outByteBuffer.array();
                }
            }
        } else {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale));
        }
        if (inputByteArray == null) {
            Debug.logError("Error in PDF generation: ", module);
            return ServiceUtil.returnError("The array used to create outByteBuffer is still declared null");
        }
        ByteBuffer outByteBuffer = ByteBuffer.wrap(inputByteArray);
        results.put("outByteBuffer", outByteBuffer);
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.toString());
    } catch (IOException | GeneralException e) {
        Debug.logError(e, "Error in PDF generation: ", module);
        return ServiceUtil.returnError(e.toString());
    }
    return results;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) ViewHandlerException(org.apache.ofbiz.webapp.view.ViewHandlerException) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) IOException(java.io.IOException) Document(com.lowagie.text.Document) ByteBuffer(java.nio.ByteBuffer) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 24 with Document

use of com.lowagie.text.Document in project cytoscape-impl by cytoscape.

the class PDFWriter method run.

@Override
public void run(TaskMonitor taskMonitor) throws Exception {
    // TODO should be accomplished with renderer properties
    // view.setPrintingTextAsShape(!exportTextAsFont);
    taskMonitor.setProgress(0.0);
    taskMonitor.setStatusMessage("Creating PDF image...");
    logger.debug("PDF Rendering start");
    final Rectangle pageSize = PageSize.LETTER;
    final Document document = new Document(pageSize);
    logger.debug("Document created: " + document);
    final PdfWriter writer = PdfWriter.getInstance(document, stream);
    document.open();
    taskMonitor.setProgress(0.1);
    final PdfContentByte canvas = writer.getDirectContent();
    logger.debug("CB0 created: " + canvas.getClass());
    final float pageWidth = pageSize.getWidth();
    final float pageHeight = pageSize.getHeight();
    logger.debug("Page W: " + pageWidth + " Page H: " + pageHeight);
    final DefaultFontMapper fontMapper = new DefaultFontMapper();
    logger.debug("FontMapper created = " + fontMapper);
    Graphics2D g = null;
    logger.debug("!!!!! Enter block 2");
    engine.getProperties().setProperty("exportTextAsShape", new Boolean(!exportTextAsFont).toString());
    taskMonitor.setProgress(0.2);
    if (exportTextAsFont) {
        g = canvas.createGraphics(pageWidth, pageHeight, new DefaultFontMapper());
    } else {
        g = canvas.createGraphicsShapes(pageWidth, pageHeight);
    }
    taskMonitor.setProgress(0.4);
    logger.debug("##### G2D created: " + g);
    double imageScale = Math.min(pageSize.getWidth() / width, pageSize.getHeight() / height);
    g.scale(imageScale, imageScale);
    logger.debug("##### Start Rendering Phase 2: " + engine.toString());
    engine.printCanvas(g);
    logger.debug("##### Canvas Rendering Done: ");
    taskMonitor.setProgress(0.8);
    g.dispose();
    document.close();
    writer.close();
    stream.close();
    logger.debug("PDF rendering finished.");
    taskMonitor.setProgress(1.0);
}
Also used : PdfWriter(com.lowagie.text.pdf.PdfWriter) Rectangle(com.lowagie.text.Rectangle) PdfContentByte(com.lowagie.text.pdf.PdfContentByte) DefaultFontMapper(com.lowagie.text.pdf.DefaultFontMapper) Document(com.lowagie.text.Document) Graphics2D(java.awt.Graphics2D)

Example 25 with Document

use of com.lowagie.text.Document in project vcell by virtualcell.

the class ITextWriter method createDocument.

protected void createDocument(PageFormat pageFormat) {
    Rectangle pageSize = new Rectangle((float) pageFormat.getWidth(), (float) pageFormat.getHeight());
    double marginL = pageFormat.getImageableX();
    double marginT = pageFormat.getImageableY();
    double marginR = pageFormat.getWidth() - pageFormat.getImageableWidth() - marginL;
    double marginB = pageFormat.getHeight() - pageFormat.getImageableHeight() - marginT;
    // System.out.println(pageFormat.getWidth() +  " " + pageFormat.getHeight() + " " + marginL + " " + marginT);
    ITextWriter.DEF_IMAGE_WIDTH = (int) pageFormat.getImageableWidth();
    // ITextWriter.DEF_IMAGE_HEIGHT = (int)pageFormat.getImageableHeight();
    // can also use some of the built-in PageSize objects, like PageSize.A4, PageSize.LETTER
    this.document = new Document(pageSize, (float) marginL, (float) marginR, (float) marginT, (float) marginB);
}
Also used : Rectangle(com.lowagie.text.Rectangle) Document(com.lowagie.text.Document)

Aggregations

Document (com.lowagie.text.Document)36 DocumentException (com.lowagie.text.DocumentException)20 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 PdfWriter (com.lowagie.text.pdf.PdfWriter)13 Paragraph (com.lowagie.text.Paragraph)12 IOException (java.io.IOException)12 Rectangle (com.lowagie.text.Rectangle)10 PdfContentByte (com.lowagie.text.pdf.PdfContentByte)9 FileOutputStream (java.io.FileOutputStream)9 Color (java.awt.Color)8 DefaultFontMapper (com.lowagie.text.pdf.DefaultFontMapper)6 PdfImportedPage (com.lowagie.text.pdf.PdfImportedPage)5 File (java.io.File)5 DocWriter (com.lowagie.text.DocWriter)4 Phrase (com.lowagie.text.Phrase)4 PdfPCell (com.lowagie.text.pdf.PdfPCell)4 PdfPTable (com.lowagie.text.pdf.PdfPTable)4 PdfReader (com.lowagie.text.pdf.PdfReader)4 Graphics2D (java.awt.Graphics2D)4 OutputStream (java.io.OutputStream)4