Package com.lowagie.text

Examples of com.lowagie.text.Document


       
        //create the document                
        Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize());               
        Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); //rotate if we need landscape
       
        Document document = new Document(pageSize)
       
       
        try {
           
            //Basic setup of the Document, and get instance of the iText Graphics2D
            //   to pass along to uDig's standard "printing" code.
            String outputFile = page1.getDestinationDir()+
                System.getProperty("file.separator")+ //$NON-NLS-1$
                page1.getOutputFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
            document.open();           
            Graphics2D graphics = null;
            Template template = getTemplate();
           
            int i = 0;
            int numPages = 1;
            do {
               
                //sets the active page
                template.setActivePage(i);
               
                PdfContentByte cb = writer.getDirectContent();    
               
                Page page = makePage(pageSize, document, template);
               
                graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight());
                        
                //instantiate a PrinterEngine (pass in the Page instance)
                PrintingEngine engine = new PrintingEngine(page);
               
                //make page format
                PageFormat pageFormat = new PageFormat();
                pageFormat.setOrientation(PageFormat.PORTRAIT);
                java.awt.print.Paper awtPaper = new java.awt.print.Paper();
                awtPaper.setSize(pageSize.getWidth() * 3, pageSize.getHeight() *3);
                awtPaper.setImageableArea(0, 0, pageSize.getWidth(), pageSize.getHeight());
                pageFormat.setPaper(awtPaper);
               
                //run PrinterEngine's print function
                engine.print(graphics, pageFormat, 0);
                 
                graphics.dispose();
                document.newPage();
                if (i == 0) {
                    numPages = template.getNumPages();
                }
                i++;
               
            } while (i < numPages);
           
            //cleanup
            document.close();
            writer.close();
        }
        catch (DocumentException e) {
            e.printStackTrace();
            return false;
View Full Code Here


     * @throws FileNotFoundException
     * @throws IOException
     */
    public void writeAll() throws FileNotFoundException, IOException{
        // Creation of a document object
        Document document = new Document();

        // Variable declaration and initialization
        ResultManager rm = new ResultManager(result);
        GraphResultDrawer graphDrawer = rm.getGraphDrawer();
        Image[] images = graphDrawer.getGraphImages();

        // Add the data into the PDF file based on the page
        // layout that the user chosen
        if(pageSetup == false) {
            // Set the page layout as landscape
            document = new Document(PageSize.LETTER.rotate());
            addDataLandscape(document, images);
        }else if(pageSetup == true) {
            addDataPortrait(document, images);
        }       
  }
View Full Code Here

        GenericValue userLogin = (GenericValue) context.get("userLogin");

        try {
            //Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
            //ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Document document = new Document();
            document.setPageSize(PageSize.LETTER);
            //Rectangle rect = document.getPageSize();
            //PdfCopy writer = new PdfCopy(document, baos);
            document.open();

            GenericValue dataResource = null;
            if (UtilValidate.isEmpty(contentRevisionSeqId)) {
                GenericValue content = delegator.findByPrimaryKeyCache("Content", UtilMisc.toMap("contentId", contentId));
                dataResourceId = content.getString("dataResourceId");
View Full Code Here

        Map 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 = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
                if (surveyResponse != null) {
                    surveyId = surveyResponse.getString("surveyId");
                }
            }
            if (UtilValidate.isNotEmpty(surveyId) && UtilValidate.isEmpty(contentId)) {
                GenericValue survey = delegator.findByPrimaryKey("Survey", UtilMisc.toMap("surveyId", surveyId));
                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 responses = delegator.findByAnd("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId));
            Iterator iter = responses.iterator();
            while (iter.hasNext()) {
                String value = null;
                GenericValue surveyResponseAnswer = (GenericValue) iter.next();
                String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
                GenericValue surveyQuestion = delegator.findByPrimaryKey("SurveyQuestion", UtilMisc.toMap("surveyQuestionId", surveyQuestionId));
                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 e) {
            System.err.println(e.getMessage());
View Full Code Here

        Map results = ServiceUtil.returnSuccess();
        String surveyResponseId = (String)context.get("surveyResponseId");
        String surveyId = null;
        List qAndA = FastList.newInstance();

        Document document = new Document();
        try {
            if (UtilValidate.isNotEmpty(surveyResponseId)) {
                GenericValue surveyResponse = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
                if (surveyResponse != null) {
                    surveyId = surveyResponse.getString("surveyId");
View Full Code Here

            Set selectFields = UtilMisc.toSetArray(fields);
            List orderByFields = UtilMisc.toList("sequenceNum");
            List compDocParts = delegator.findList("ContentAssocRevisionItemView", conditionList, selectFields, orderByFields, null, false);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Document document = new Document();
            document.setPageSize(PageSize.LETTER);
            //Rectangle rect = document.getPageSize();
            //PdfWriter writer = PdfWriter.getInstance(document, baos);
            PdfCopy writer = new PdfCopy(document, baos);
            document.open();
            Iterator iter = compDocParts.iterator();
            int pgCnt =0;
            while (iter.hasNext()) {
                GenericValue contentAssocRevisionItemView = (GenericValue)iter.next();
                //String thisContentId = contentAssocRevisionItemView.getString("contentId");
                //String thisContentRevisionSeqId = contentAssocRevisionItemView.getString("maxRevisionSeqId");
                String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
                GenericValue dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", thisDataResourceId));
                String inputMimeType = null;
                if (dataResource != null) {
                    inputMimeType = dataResource.getString("mimeTypeId");
                }
                byte [] inputByteArray = null;
                PdfReader reader = null;
                if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
                    ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
                    inputByteArray = byteBuffer.array();
                    reader = new PdfReader(inputByteArray);
                } else if (inputMimeType != null && inputMimeType.equals("text/html")) {
                    ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
                    inputByteArray = byteBuffer.array();
                    String s = new String(inputByteArray);
                    Debug.logInfo("text/html string:" + s, module);
                    continue;
                } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
                    String surveyResponseId = dataResource.getString("relatedDetailId");
                    String surveyId = null;
                    String acroFormContentId = null;
                    GenericValue surveyResponse = null;
                    if (UtilValidate.isNotEmpty(surveyResponseId)) {
                        surveyResponse = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
                        if (surveyResponse != null) {
                            surveyId = surveyResponse.getString("surveyId");
                        }
                    }
                    if (UtilValidate.isNotEmpty(surveyId)) {
                        GenericValue survey = delegator.findByPrimaryKey("Survey", UtilMisc.toMap("surveyId", surveyId));
                        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 survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId));
                            if (ServiceUtil.isError(survey2PdfResults)) {
                                return ServiceUtil.returnError("Error building PDF from SurveyResponse: ", null, null, survey2PdfResults);
                            }

                            ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
                            inputByteArray = outByteBuffer.array();
                            reader = new PdfReader(inputByteArray);
                        } else {
                            // Fill in acroForm
                            Map survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
                            if (ServiceUtil.isError(survey2AcroFieldResults)) {
                                return ServiceUtil.returnError("Error setting AcroFields from SurveyResponse: ", null, null, survey2AcroFieldResults);
                            }

                            ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
                            inputByteArray = outByteBuffer.array();
                            reader = new PdfReader(inputByteArray);
                        }
                    }
                } else {
                    ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);

                    Map convertInMap = UtilMisc.toMap("userLogin", userLogin, "inByteBuffer", inByteBuffer, "inputMimeType", inputMimeType, "outputMimeType", "application/pdf");
                    if (UtilValidate.isNotEmpty(oooHost)) convertInMap.put("oooHost", oooHost);
                    if (UtilValidate.isNotEmpty(oooPort)) convertInMap.put("oooPort", oooPort);

                    Map convertResult = dispatcher.runSync("convertDocumentByteBuffer", convertInMap);

                    if (ServiceUtil.isError(convertResult)) {
                        return ServiceUtil.returnError("Error in Open", null, null, convertResult);
                    }

                    ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer");
                    inputByteArray = outByteBuffer.array();
                    reader = new PdfReader(inputByteArray);
                }
                if (reader != null) {
                    int n = reader.getNumberOfPages();
                    for (int i=0; i < n; i++) {
                        PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
                        //cb.addTemplate(pg, left, height * pgCnt);
                        writer.addPage(pg);
                        pgCnt++;
                    }
                }
            }
            document.close();
            ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());

            Map results = ServiceUtil.returnSuccess();
            results.put("outByteBuffer", outByteBuffer);
            return results;
View Full Code Here

            // width of document-object is width*72 inches
            // height of document-object is height*72 inches
            com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(
                    width, height);

            Document document = new Document(pageSize);
            document.setMargins(0, 0, 0, 0);

            // step 2: creation of the writer
            PdfWriter writer = PdfWriter.getInstance(document, out);

            // step 3: we open the document
            document.open();

            // step 4: we grab the ContentByte and do some stuff with it

            // we create a fontMapper and read all the fonts in the font
            // directory
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();

            // we create a template and a Graphics2D object that corresponds
            // with it
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper);

            // we set graphics options
            if (!mapContext.isTransparent()) {
                graphic.setColor(mapContext.getBgColor());
                graphic.fillRect(0, 0, width, height);
            } else {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine("setting to transparent");
                }

                int type = AlphaComposite.SRC;
                graphic.setComposite(AlphaComposite.getInstance(type));

                Color c = new Color(mapContext.getBgColor().getRed(),
                        mapContext.getBgColor().getGreen(), mapContext
                                .getBgColor().getBlue(), 0);
                graphic.setBackground(mapContext.getBgColor());
                graphic.setColor(c);
                graphic.fillRect(0, 0, width, height);

                type = AlphaComposite.SRC_OVER;
                graphic.setComposite(AlphaComposite.getInstance(type));
            }

            Rectangle paintArea = new Rectangle(width, height);

            renderer = new StreamingRenderer();
            renderer.setContext(mapContext);
            // TODO: expose the generalization distance as a param
            // ((StreamingRenderer) renderer).setGeneralizationDistance(0);

            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            renderer.setJava2DHints(hints);

            // we already do everything that the optimized data loading does...
            // if we set it to true then it does it all twice...
            Map rendererParams = new HashMap();
            rendererParams
                    .put("optimizedDataLoadingEnabled", new Boolean(true));
            rendererParams.put("renderingBuffer", new Integer(mapContext
                    .getBuffer()));
            // we need the renderer to draw everything on the batik provided graphics object
            rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE);
            // render everything in vector form if possible
            rendererParams.put(StreamingRenderer.VECTOR_RENDERING_KEY, Boolean.TRUE);
            if(DefaultWebMapService.isLineWidthOptimizationEnabled()) {
                rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, true);
            }
            if(DefaultWebMapService.isAdvancedProjectionHandlingEnabled()) {
                rendererParams.put(StreamingRenderer.ADVANCED_PROJECTION_HANDLING_KEY, true);
            }
            renderer.setRendererHints(rendererParams);

            Envelope dataArea = mapContext.getAreaOfInterest();

            if (this.abortRequested) {
                graphic.dispose();
                // step 5: we close the document
                document.close();

                return;
            }
           
            // enforce no more than x rendering errors
            int maxErrors = wms.getMaxRenderingErrors();
            MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors);

            // Add a render listener that ignores well known rendering exceptions and reports back non
            // ignorable ones
            final RenderExceptionStrategy nonIgnorableExceptionListener;
            nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer);
            renderer.addRenderListener(nonIgnorableExceptionListener);
           
            // enforce max memory usage
            int maxMemory = wms.getMaxRequestMemory() * KB;
            PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory);
           
            // render the map
            renderer.paint(graphic, paintArea, getRenderingArea(), getRenderingTransform());
           
            // render the watermark
            MapDecorationLayout.Block watermark =
                DefaultRasterMapProducer.getWatermark(this.mapContext.getRequest().getWMS().getServiceInfo());

            if (watermark != null) {
                MapDecorationLayout layout = new MapDecorationLayout();
                layout.paint(graphic, paintArea, this.mapContext);
            }
           
            //check if a non ignorable error occurred
            if(nonIgnorableExceptionListener.exceptionOccurred()){
                Exception renderError = nonIgnorableExceptionListener.getException();
                throw new WmsException("Rendering process failed", "internalError", renderError);
            }

            // check if too many errors occurred
            if(errorChecker.exceedsMaxErrors()) {
                throw new WmsException("More than " + maxErrors + " rendering errors occurred, bailing out",
                        "internalError", errorChecker.getLastException());
            }
           
            // check we did not use too much memory
            if(memoryChecker.exceedsMaxSize()) {
                long kbMax = maxMemory / KB;
                throw new WmsException("Rendering request used more memory than the maximum allowed:"
                        + kbMax + "KB");
            }

            graphic.dispose();
            cb.addTemplate(tp, 0, 0);

            // step 5: we close the document
            document.close();
            writer.flush();
            writer.close();
        } catch (DocumentException t) {
            throw new WmsException("Error setting up the PDF", "internalError", t);
        }
View Full Code Here

  public PdfCreator() {
   // for Class.forName 
  }
 
  public String createPdfDocument(String fileName, Image image) {
    Document document = new Document();
    File file = null;
    try {
      int w = image.getWidth(null);
      int h = image.getHeight(null);
      file = new File(fileName);
      PdfWriter writer = PdfWriter.getInstance(document,
          new FileOutputStream(file));
      document.open();
      PdfContentByte cb = writer.getDirectContent();
      PdfTemplate tp = cb.createTemplate(w, h);
      Graphics2D g2 = tp.createGraphics(w, h);
      g2.setStroke(new BasicStroke(0.1f));
      tp.setWidth(w);
      tp.setHeight(h);
      g2.drawImage(image, 0, 0, w, h, 0, 0, w, h, null);
      g2.dispose();
      cb.addTemplate(tp, 72, 720 - h);
    } catch (DocumentException de) {
      return de.getMessage();
    } catch (IOException ioe) {
      return ioe.getMessage();
    }
    document.close();
    return null;
  }
View Full Code Here

   
    private static void writeAsPDF(OutputStream out, AbstractEnvironment2D<?> env, FontMapper mapper) {
        int width = (int) env.getScreenWidth();
        int height = (int) env.getScreenHeight();
        Rectangle pagesize = new Rectangle(width , height);
        Document document = new Document(pagesize, 50, 50, 50, 50);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, out);
            document.addAuthor("EAS-StaticMethods");
            document.addSubject("EAS-StandardSubject");
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            Graphics2D g2 = tp.createGraphics(width, height, mapper);
            env.getOutsideView(g2);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        }
        document.close();
    }
View Full Code Here

     * This code is taken from the JFreeChart documentation.
     */
    public static void writeChartAsPDF(OutputStream out, JFreeChart chart,
            int width, int height, FontMapper mapper) {
        Rectangle pagesize = new Rectangle(width, height);
        Document document = new Document(pagesize, 50, 50, 50, 50);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, out);
            document.addAuthor("EAS-ChartPlugin");
            document.addSubject(chart.getTitle().getText());
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            Graphics2D g2 = tp.createGraphics(width, height, mapper);
            java.awt.geom.Rectangle2D r2D = new java.awt.geom.Rectangle2D.Double(0, 0, width, height);
            chart.draw(g2, r2D);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        }
        document.close();
    }
View Full Code Here

TOP

Related Classes of com.lowagie.text.Document

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.