Package com.lowagie.text

Examples of com.lowagie.text.Document


        int n = pdfReader.getNumberOfPages();
        BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n);
        int fileNum = 0;
        LOG.info("Found " + n + " pages in input pdf document.");
        int currentPage;
        Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
        PdfImportedPage importedPage;
        File tmpFile = null;
        File outFile = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int startPage = 0;
        int relativeCurrentPage = 0;
        for (currentPage = 1; currentPage <= n; currentPage++) {
            relativeCurrentPage++;
            // time to open a new document?
            if (relativeCurrentPage == 1) {
                LOG.debug("Creating a new document.");
                startPage = currentPage;
                fileNum++;
                tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
                FileNameRequest request = new FileNameRequest(currentPage, fileNum, null);
                outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
                currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));
                baos = new ByteArrayOutputStream();
                pdfWriter = new PdfSmartCopy(currentDocument, baos);
                // set creator
                currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

                setCompressionSettingOnWriter(inputCommand, pdfWriter);
                setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

                currentDocument.open();
            }

            importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
            pdfWriter.addPage(importedPage);
            // if it's time to close the document
            if ((currentPage == n)
                    || ((relativeCurrentPage > 1) && ((baos.size() / relativeCurrentPage) * (1 + relativeCurrentPage) > inputCommand
                            .getSplitSize().longValue()))) {
                LOG.debug("Current stream size: " + baos.size() + " bytes.");
                // manage bookmarks
                List bookmarks = bookmarkProcessor.processBookmarks(startPage, currentPage);
                if (bookmarks != null) {
                    pdfWriter.setOutlines(bookmarks);
                }
                relativeCurrentPage = 0;
                currentDocument.close();
                FileOutputStream fos = new FileOutputStream(tmpFile);
                baos.writeTo(fos);
                fos.close();
                baos.close();
                LOG.info("Temporary document " + tmpFile.getName() + " done.");
View Full Code Here


  public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {
    if((parsedCommand != null) && (parsedCommand instanceof PageLabelsParsedCommand)){

      PageLabelsParsedCommand inputCommand = (PageLabelsParsedCommand) parsedCommand;
      setPercentageOfWorkDone(0);
      Document currentDocument;
      try{                               
        File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
        LOG.debug("Opening "+inputCommand.getInputFile().getFile().getAbsolutePath());
        pdfReader = new PdfReader(new RandomAccessFileOrArray(inputCommand.getInputFile().getFile().getAbsolutePath()),inputCommand.getInputFile().getPasswordBytes());
        pdfReader.removeUnusedObjects();
          pdfReader.consolidateNamedDestinations();
          int n = pdfReader.getNumberOfPages();
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
           
              pdfWriter = new PdfCopy(currentDocument, new FileOutputStream(tmpFile));
           
              //set compressed
        setCompressionSettingOnWriter(inputCommand, pdfWriter);    
              //set pdf version
        setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));
           
        //set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);
            currentDocument.open();
           
        for (int count = 1; count <= n; count++) {
          pdfWriter.addPage(pdfWriter.getImportedPage(pdfReader, count));                               
              }
        pdfReader.close();
              pdfWriter.freeReader(pdfReader);
             
        //set labels
        PdfPageLabels pageLabels = new PdfPageLabels();
        PageLabel[] labels = inputCommand.getLabels();
        //last step is creating the file
        int stepsNumber = labels.length + 1;
        for(int i=0; i<labels.length; i++){
          if(labels[i].getPageNumber()<=n){
            pageLabels.addPageLabel(labels[i].getPageNumber(), getPageLabelStyle(labels[i].getStyle()), labels[i].getPrefix(), labels[i].getLogicalPageNumber());
          }else{
            LOG.warn("Page number out of range, label starting at page "+labels[i].getPageNumber()+" will be ignored");
          }
          setPercentageOfWorkDone((i*WorkDoneDataModel.MAX_PERGENTAGE)/stepsNumber);
        }       
        pdfWriter.setPageLabels(pageLabels);
       
          currentDocument.close();         
          pdfWriter.close();
              FileUtility.renameTemporaryFile(tmpFile, inputCommand.getOutputFile(), inputCommand.isOverwrite());
              LOG.debug("Page labels set on file "+inputCommand.getOutputFile());
      }catch(Exception e){  
        throw new PageLabelsException(e);
View Full Code Here

    public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {
        if ((parsedCommand != null) && (parsedCommand instanceof MixParsedCommand)) {
            MixParsedCommand inputCommand = (MixParsedCommand) parsedCommand;
            setWorkIndeterminate();
            Document pdfDocument = null;

            int[] limits1 = { 1, 1 };
            int[] limits2 = { 1, 1 };
            try {
                File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());

                pdfReader1 = new PdfReader(new RandomAccessFileOrArray(inputCommand.getFirstInputFile().getFile()
                        .getAbsolutePath()), inputCommand.getFirstInputFile().getPasswordBytes());
                pdfReader1.removeUnusedObjects();
                pdfReader1.consolidateNamedDestinations();
                limits1[1] = pdfReader1.getNumberOfPages();

                pdfReader2 = new PdfReader(new RandomAccessFileOrArray(inputCommand.getSecondInputFile().getFile()
                        .getAbsolutePath()), inputCommand.getSecondInputFile().getPasswordBytes());
                pdfReader2.removeUnusedObjects();
                pdfReader2.consolidateNamedDestinations();
                limits2[1] = pdfReader2.getNumberOfPages();

                pdfDocument = new Document(pdfReader1.getPageSizeWithRotation(1));
                LOG.debug("Creating a new document.");
                pdfWriter = new PdfCopy(pdfDocument, new FileOutputStream(tmpFile));

                setPdfVersionSettingOnWriter(inputCommand, pdfWriter);
                setCompressionSettingOnWriter(inputCommand, pdfWriter);

                pdfDocument.addCreator(ConsoleServicesFacade.CREATOR);
                pdfDocument.open();

                PdfImportedPage page;

                boolean finished1 = false;
                boolean finished2 = false;
                int current1 = (inputCommand.isReverseFirst()) ? limits1[1] : limits1[0];
                int current2 = (inputCommand.isReverseSecond()) ? limits2[1] : limits2[0];
                while (!finished1 || !finished2) {
                    if (!finished1) {
                        for (int i = 0; (i < inputCommand.getStep() && !finished1); i++) {
                            if (current1 >= limits1[0] && current1 <= limits1[1]) {
                                page = pdfWriter.getImportedPage(pdfReader1, current1);
                                pdfWriter.addPage(page);
                                current1 = (inputCommand.isReverseFirst()) ? (current1 - 1) : (current1 + 1);
                            } else {
                                LOG.info("First file processed.");
                                pdfReader1.close();
                                finished1 = true;
                            }
                        }
                    }
                    if (!finished2) {
                        for (int i = 0; (i < inputCommand.getSecondStep() && !finished2); i++) {
                            if (current2 >= limits2[0] && current2 <= limits2[1] && !finished2) {
                                page = pdfWriter.getImportedPage(pdfReader2, current2);
                                pdfWriter.addPage(page);
                                current2 = (inputCommand.isReverseSecond()) ? (current2 - 1) : (current2 + 1);
                            } else {
                                LOG.info("Second file processed.");
                                pdfReader2.close();
                                finished2 = true;
                            }
                        }
                    }

                }

                pdfWriter.freeReader(pdfReader1);
                pdfWriter.freeReader(pdfReader2);

                pdfDocument.close();
                FileUtility.renameTemporaryFile(tmpFile, inputCommand.getOutputFile(), inputCommand.isOverwrite());
                LOG.debug("File " + inputCommand.getOutputFile().getCanonicalPath() + " created.");
                LOG.info("Alternate mix with step first document " + inputCommand.getStep()
                        + " and step second document " + inputCommand.getSecondStep() + " completed.");
            } catch (Exception e) {
View Full Code Here

        super.endDocument();
        getLogger().debug("finished PDF document");
    }

    public void setOutputStream(OutputStream out) {
        this.document = new Document(this.pageSize);

        try {
            PdfWriter.getInstance(document, out);
        }
        catch(Exception e) {
View Full Code Here

    private Font facetFont;
      
  @Override
  public void export(FacesContext context, DataTable table, String filename, boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor, MethodExpression postProcessor) throws IOException {
    try {
          Document document = new Document();
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          PdfWriter.getInstance(document, baos);
         
          if (preProcessor != null) {
          preProcessor.invoke(context.getELContext(), new Object[]{document});
        }

            if (!document.isOpen()) {
                document.open();
            }
         
        document.add(exportPDFTable(context, table, pageOnly, selectionOnly, encodingType));
       
        if(postProcessor != null) {
          postProcessor.invoke(context.getELContext(), new Object[]{document});
        }
       
          document.close();
       
          writePDFToResponse(context.getExternalContext(), baos, filename);
         
    } catch(DocumentException e) {
      throw new IOException(e.getMessage());
View Full Code Here

      myFilePath.delete();
      myFilePath.createNewFile();
    }

    // 打开rtf文档
    Document document = new Document();
    FileOutputStream myFile = new FileOutputStream(filePath);
    RtfWriter2 rtfWriter2 = RtfWriter2.getInstance(document, myFile);
    document.open();
    // TODO 加文档标题,即项目名 有待居中
    RtfFont projectNameFont = new RtfFont("Arial", 35, RtfFont.STYLE_BOLD);
    Paragraph paragraph = new Paragraph();
    // Use the RtfFonts when creating the text.
    paragraph.add(new Chunk(projectName, projectNameFont));
    Paragraph paragraph2 = new Paragraph();
    // Use the RtfFonts when creating the text.
    paragraph2.add(new Chunk("需求文档", projectNameFont));

    paragraph.setAlignment(1);
    paragraph2.setAlignment(1);
    document.add(paragraph);
    document.add(paragraph2);
    // 加Table of Content
    RtfParagraphStyle tocLevel1Style = new RtfParagraphStyle("toc 1",
        "Times New Roman", 11, Font.NORMAL, Color.BLACK);
    RtfParagraphStyle tocLevel2Style = new RtfParagraphStyle("toc 2",
        "Times New Roman", 10, Font.NORMAL, Color.BLACK);
    tocLevel2Style.setIndentLeft(10);

    // Register the paragraph stylesheets with the RtfWriter2
    rtfWriter2.getDocumentSettings().registerParagraphStyle(tocLevel1Style);
    rtfWriter2.getDocumentSettings().registerParagraphStyle(tocLevel2Style);

    // Create a Paragraph and add the table of contents to it
    Paragraph par = new Paragraph();

    par.add(new RtfTableOfContents("如想查看目录,单击右键选择\"更新域\""));
    par.setAlignment(1);
    document.add(par);

    CompositeDataProxy cdp = CompositeDataProxy.getInstance();
    SingleDataProxy sdp = SingleDataProxy.getInstance();
    Project p = new Project();
    p.setProjectName(projectName);
    p = (Project) sdp.get(p);
    // 得到该项目的所有的场景
    Scenario s = new Scenario();
    s.setProjectId(p.getProjectId());
    scenarios = cdp.query(s);
    if (scenarios.size() > 0) {
      for (int i = 0; i < scenarios.size(); i++) {
        s = (Scenario) scenarios.get(i);
        document.add(new Paragraph(""));
        // 加场景名
        document.add(new Paragraph("场景" + (i + 1) + ": "
            + s.getScenarioName().toString(),
            RtfParagraphStyle.STYLE_HEADING_1));
        // TODO 加用况
        UseCase uc = new UseCase();
        uc.setScenarioId(s.getScenarioId());
        ArrayList ucs = cdp.query(uc);
        if (ucs.size() > 0) {
          for (int j = 0; j < ucs.size(); j++) {

            uc = (UseCase) ucs.get(j);
            document.add(new Paragraph(""));
            document.add(new Paragraph("用况" + (i + 1) + "."
                + (j + 1) + ": "
                + uc.getUseCaseName().toString(),
                RtfParagraphStyle.STYLE_HEADING_2));

            RtfBorderGroup normal = new RtfBorderGroup(
                Rectangle.BOX, RtfBorder.BORDER_SINGLE, 1,
                new Color(0, 0, 0));

            Paragraph title = new Paragraph();
            title.add(new Chunk(uc.getUseCaseName().trim()));
            title.setAlignment(1);
            document.add(title);

            RtfCell useCaseID = new RtfCell("用况编号:");
            useCaseID.setBorders(normal);

            RtfCell useCaseIDC = new RtfCell(uc.getUseCaseId()
                .toString());
            useCaseIDC.setBorders(normal);

            RtfCell useCaseName = new RtfCell("用况名称:");
            useCaseName.setBorders(normal);

            RtfCell useCaseNameC = new RtfCell(uc.getUseCaseName());
            useCaseNameC.setBorders(normal);

            RtfCell useCaseDescription = new RtfCell("用况描述:");
            useCaseDescription.setBorders(normal);

            RtfCell useCaseDescriptionC = new RtfCell(uc
                .getUseCaseDescription());
            useCaseDescriptionC.setBorders(normal);

            RtfCell useCasePriority = new RtfCell("用况优先级:");
            useCasePriority.setBorders(normal);

            RtfCell useCasePriorityC = null;

            if (uc.getUseCasePriority() != null) {
              useCasePriorityC = new RtfCell(uc
                  .getUseCasePriority().toString());
            } else {
              useCasePriorityC = new RtfCell("");
            }

            useCasePriorityC.setBorders(normal);

            RtfCell specialRequirement = new RtfCell("特殊要求:");
            specialRequirement.setBorders(normal);

            RtfCell specialRequirementC = new RtfCell(uc
                .getUseCaseSpecialRequirement());
            specialRequirementC.setColspan(3);
            specialRequirementC.setBorders(normal);

            RtfCell preCondition = new RtfCell("前置条件:");
            preCondition.setBorders(normal);

            RtfCell preConditionC = new RtfCell(uc
                .getUseCasePreconditions());
            preConditionC.setColspan(3);
            preConditionC.setBorders(normal);

            RtfCell fireCondition = new RtfCell("触发条件:");
            fireCondition.setBorders(normal);

            RtfCell fireConditionC = new RtfCell(uc
                .getUseCaseTrigger());
            fireConditionC.setColspan(3);
            fireConditionC.setBorders(normal);

            RtfCell postCondition = new RtfCell("后置条件:");
            postCondition.setBorders(normal);

            RtfCell postConditionC = new RtfCell(uc
                .getUseCasePostConditions());
            postConditionC.setColspan(3);
            postConditionC.setBorders(normal);

            RtfCell failedEndCondition = new RtfCell("失败情况:");
            failedEndCondition.setBorders(normal);

            RtfCell failedEndConditionC = new RtfCell(uc
                .getUseCaseFailedEndCondition());
            failedEndConditionC.setColspan(3);
            failedEndConditionC.setBorders(normal);

            Table table = new Table(4);
            table.addCell(useCaseID);
            table.addCell(useCaseIDC);
            table.addCell(useCaseName);
            table.addCell(useCaseNameC);
            table.addCell(useCaseDescription);
            table.addCell(useCaseDescriptionC);
            table.addCell(useCasePriority);
            table.addCell(useCasePriorityC);
           
            table.addCell(fireCondition);
            table.addCell(fireConditionC);
            table.addCell(preCondition);
            table.addCell(preConditionC);
            table.addCell(failedEndCondition);
            table.addCell(failedEndConditionC);
            table.addCell(postCondition);
            table.addCell(postConditionC);         
            table.addCell(specialRequirement);
            table.addCell(specialRequirementC);

            // 生成Use Case具体描述的标题

            RtfCell userOperation = new RtfCell("用户操作");
            userOperation.setBorders(normal);

            RtfCell systemOperation = new RtfCell("系统操作");
            systemOperation.setBorders(normal);

            RtfCell systemOutput = new RtfCell("系统输出");
            systemOutput.setBorders(normal);

            Table table2 = new Table(3);
            table2.addCell(userOperation);
            table2.addCell(systemOperation);
            table2.addCell(systemOutput);

            // 生成Use Case具体描述的内容
            ArrayList ucis = new ArrayList();

            UseCaseInteraction uci = new UseCaseInteraction();
            uci.setUseCaseId(uc.getUseCaseId());
            OrderRule orderule = new OrderRule();
            orderule.setOrderColumn("sequence");
            orderule.setOrderDirection(OrderDirection.ASC);
            OrderRule[] orderRules = { orderule };
            String temp;
            ucis = cdp.query(uci, orderRules);
            if (ucis.size() > 0) {
              for (int k = 0; k < ucis.size(); k++) {
                temp = ((UseCaseInteraction) ucis.get(k))
                    .getOperatorAction();
                temp = removeHtml(temp);
                RtfCell userOperationC = new RtfCell(temp);
                userOperationC.setBorders(normal);

                temp = ((UseCaseInteraction) ucis.get(k))
                    .getSystemAction();
                temp = removeHtml(temp);
                RtfCell systemOperationC = new RtfCell(temp);
                systemOperationC.setBorders(normal);

                temp = ((UseCaseInteraction) ucis.get(k))
                    .getSystemOutput();
                temp = removeHtml(temp);
                RtfCell systemOutputC = new RtfCell(temp);
                systemOutputC.setBorders(normal);
                table2.addCell(userOperationC);
                table2.addCell(systemOperationC);
                table2.addCell(systemOutputC);
              }

            } else {

            }
            //

            document.add(table);
            document.add(table2);

          }

        } else {
          // TODO 暂无用况的时候
          document.add(new Paragraph(""));
          Paragraph noUseCase = new Paragraph();
          noUseCase.add(new Chunk("暂无用况"));
          document.add(noUseCase);
        }
      }

    } else {
      // TODO 加场景名 暂无场景的时候
    }

    document.close();
    myFile.close();
    rtfWriter2.close();

    return myFilePath;
  }
View Full Code Here

    // See http://www.lowagie.com/iText/faq.html#msie
    // for an explanation of why we can't use the obvious form above.

    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE);
    Document document = newDocument();
    PdfWriter writer = newWriter(document, baos);

    // Apply preferences and build metadata.
    prepareWriter(model, writer, request);
    buildPdfMetadata(model, document, request);

    // Build PDF document.
    document.open();
    buildPdfDocument(model, document, writer, request, response);
    document.close();

    // Write content type and also length (determined via byte array).
    response.setContentType(getContentType());
    response.setContentLength(baos.size());
View Full Code Here

   * Document, possibly parameterized via bean properties defined on the View.
   * @return the newly created iText Document instance
   * @see com.lowagie.text.Document#Document(com.lowagie.text.Rectangle)
   */
  protected Document newDocument() {
    return new Document(PageSize.A4);
  }
View Full Code Here

    public void saveReport(File file, Localidad[] localidades, BufferedImage image, Map<String, String> params, Map<String, String> systemProperties) throws Exception {

        this.parameters = params;

        //create A4 document, set margins
        Document document = new Document(PageSize.A4, 40, 40, 170, 60);

        //create PdfWriter to file
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

        //handle document events so headers/footers can be written
        writer.setPageEvent(this);

        document.open();

        //add application information read from parameters map
        document.add(new Chunk("\n"));
        PdfPTable mapInfo = new PdfPTable(1);
        {
            mapInfo.getDefaultCell().setBorderWidth(0);

            Paragraph header = new Paragraph("Información resultado\n\n", new Font(Font.HELVETICA, 14, Font.BOLDITALIC));
            PdfPCell cell = new PdfPCell(header);
            cell.setColspan(1);
            cell.setBorderWidth(0);
            mapInfo.addCell(cell);

            PdfPTable subTable = new PdfPTable(1);
            subTable.getDefaultCell().setBorderWidth(0);

            Paragraph p = new Paragraph();
            Font f = new Font(Font.COURIER, 12);

            Iterator iterator = params.keySet().iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                String name = key + ":";
                while (name.length() < 23) {
                    name += " ";
                }
                p.add(new Chunk(" " + name + params.get(key) + "\n", f));
            }

            subTable.addCell(p);
            mapInfo.addCell(subTable);
            mapInfo.setWidthPercentage(100);
            document.add(mapInfo);
        }

        //add system information
        PdfPTable systemInfo = new PdfPTable(1);
        {
            systemInfo.getDefaultCell().setBorderWidth(0);

            Paragraph header = new Paragraph("\n\nInformación Sistema\n\n", new Font(Font.HELVETICA, 14, Font.BOLDITALIC));
            PdfPCell cell = new PdfPCell(header);
            cell.setColspan(1);
            cell.setBorderWidth(0);
            systemInfo.addCell(cell);

            PdfPTable subTable = new PdfPTable(1);
            subTable.getDefaultCell().setBorderWidth(0);

            Paragraph p = new Paragraph();
            Font f = new Font(Font.COURIER, 12);

            Iterator iterator = systemProperties.keySet().iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                String name = key + ":";
                while (name.length() < 23) {
                    name += " ";
                }
                p.add(new Chunk(" " + name + systemProperties.get(key) + "\n", f));
            }

            subTable.addCell(p);
            systemInfo.addCell(subTable);
            systemInfo.setWidthPercentage(100);
            document.add(systemInfo);
        }

        document.setMargins(40, 40, 30, 30);
        document.setPageSize(PageSize.A4.rotate());
        document.newPage();

        if (image != null) {
            Image img = Image.getInstance(image, null);
            img.setAlignment(Element.ALIGN_CENTER);
            document.add(img);
        }


        document.setMargins(40,40,170,60);
        document.setPageSize(PageSize.A4);
        document.newPage();

        //list table with the path through the cities and distances between them
        document.add(new Paragraph("Rutas del Problema\n\n",new Font(Font.HELVETICA, 14, Font.BOLDITALIC)));

        //create font for header and cities.
        //TODO: how to create unicode font without having to transfer .ttf file ?
        Font tableHeaderFont=new Font(BaseFont.createFont(
              BaseFont.HELVETICA,
              BaseFont.CP1250,
              BaseFont.EMBEDDED),
              12, Font.BOLD);

        //create tabe and set properties
        PdfPTable datatable = new PdfPTable(6);
        int headerwidths[] = { 5, 31, 16, 16, 16, 16}; // percentage
        datatable.setWidths(headerwidths);
        datatable.setWidthPercentage(100); // percentage
        datatable.getDefaultCell().setPadding(2);
        datatable.getDefaultCell().setBorderWidth(1);
        datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

        //header row
        PdfPCell c1=new PdfPCell(new Phrase("Barrio",tableHeaderFont));
        c1.setColspan(2);
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setVerticalAlignment(Element.ALIGN_CENTER);

        datatable.addCell(c1);
        datatable.addCell(new Phrase("X\n",tableHeaderFont));
        datatable.addCell(new Phrase("Y\n",tableHeaderFont));
        datatable.addCell(new Phrase("Distancia\n[m]",tableHeaderFont));
        datatable.addCell(new Phrase("Total\n[m]",tableHeaderFont));
        datatable.setHeaderRows(1); // this is the end of the table header

        //create fixed with font for numbers
        Font numberFont=new Font(Font.COURIER, 11);

       
        //compute the distance between two cities and total distance
        double totalDistance=0;
        for (int i = 0; i < localidades.length; i++) {
           //grey each second line
            if (i % 2 == 1) {
                datatable.getDefaultCell().setGrayFill(0.97f);
            }

            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            datatable.addCell(new Phrase(numberFormatter.format(i+1),numberFont));
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            datatable.addCell(new Phrase(localidades[i].getBarrio().getDenominacion(),tableHeaderFont));
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            datatable.addCell(new Phrase(numberFormatter.format(localidades[i].getBarrio().getCoordenadaX()),numberFont));
            datatable.addCell(new Phrase(numberFormatter.format(localidades[i].getBarrio().getCoordenadaY()),numberFont));
            String distanceText="0";
            String totalDistanceText="0";
            double distance=0;
           
               //distance=cities[i].distance(cities[i-1],false);
            distanceText=numberFormatter.format((int)distance);
            totalDistance+=distance;
            totalDistanceText=numberFormatter.format((int)totalDistance);
           
            datatable.addCell(new Phrase(distanceText,numberFont));
            datatable.addCell(new Phrase(totalDistanceText,numberFont));

            //switch of gray colour
            datatable.getDefaultCell().setGrayFill(0.0f);
        }
        document.add(datatable);

        document.close();
    }
View Full Code Here

    byte[] pdfContent = response.getContentAsByteArray();
    assertEquals("correct response content type", "application/pdf", response.getContentType());
    assertEquals("correct response content length", pdfContent.length, response.getContentLength());

    // rebuild iText document for comparison
    Document document = new Document(PageSize.A4);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    writer.setViewerPreferences(PdfWriter.AllowPrinting | PdfWriter.PageLayoutSinglePage);
    document.open();
    document.add(new Paragraph(text));
    document.close();
    byte[] baosContent = baos.toByteArray();
    assertEquals("correct size", pdfContent.length, baosContent.length);

    int diffCount = 0;
    for (int i = 0; i < pdfContent.length; i++) {
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.