Package com.lowagie.text

Examples of com.lowagie.text.Document


      Rectangle pageSize = reader.getPageSize(1);
      Rectangle newSize = new Rectangle(pageSize.width() / 2, pageSize
          .height());
      // step 1: creation of a document-object
      Document document = new Document(newSize, 0, 0, 0, 0);
      // step 2: we create a writer that listens to the document
      PdfWriter writer = PdfWriter.getInstance(document,
          new FileOutputStream(dest));
      // step 3: we open the document
      document.open();
      // step 4: adding the content
      PdfContentByte cb = writer.getDirectContent();
      PdfImportedPage page;
      float offsetX, offsetY;
      int p;
      for (int i = 0; i < total; i++) {
        p = i + 1;
        pageSize = reader.getPageSize(p);
        newSize = new Rectangle(pageSize.width() / 2, pageSize.height());

        document.newPage();
        offsetX = 0;
        offsetY = 0;
        page = writer.getImportedPage(reader, p);
        cb.addTemplate(page, 1, 0, 0, 1, offsetX, offsetY);
        document.newPage();
        offsetX = -newSize.width();
        offsetY = 0;
        page = writer.getImportedPage(reader, p);
        cb.addTemplate(page, 1, 0, 0, 1, offsetX, offsetY);

      }
      // step 5: we close the document
      document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
View Full Code Here


      if (getValue("destfile") == null) throw new InstantiationException("You need to choose a destination file");
      File pdf_file = (File)getValue("destfile");
      RandomAccessFileOrArray ra = new RandomAccessFileOrArray(tiff_file.getAbsolutePath());
            int comps = TiffImage.getNumberOfPages(ra);
      boolean adjustSize = false;
      Document document = new Document(PageSize.A4);
            float width = PageSize.A4.width() - 40;
            float height = PageSize.A4.height() - 120;
      if ("ORIGINAL".equals(getValue("pagesize"))) {
        Image img = TiffImage.getTiffImage(ra, 1);
                if (img.getDpiX() > 0 && img.getDpiY() > 0) {
                    img.scalePercent(7200f / img.getDpiX(), 7200f / img.getDpiY());
                }
        document.setPageSize(new Rectangle(img.scaledWidth(), img.scaledHeight()));
        adjustSize = true;
      }
      else if ("LETTER".equals(getValue("pagesize"))) {
        document.setPageSize(PageSize.LETTER);
                width = PageSize.LETTER.width() - 40;
                height = PageSize.LETTER.height() - 120;
      }
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file));
      document.open();
      PdfContentByte cb = writer.getDirectContent();
            for (int c = 0; c < comps; ++c) {
                Image img = TiffImage.getTiffImage(ra, c + 1);
                if (img != null) {
                    if (img.getDpiX() > 0 && img.getDpiY() > 0) {
                        img.scalePercent(7200f / img.getDpiX(), 7200f / img.getDpiY());
                    }
                  if (adjustSize) {
              document.setPageSize(new Rectangle(img.scaledWidth(),
                  img.scaledHeight()));
                        document.newPage();
                    img.setAbsolutePosition(0, 0);
                  }
                  else {
                    if (img.scaledWidth() > width || img.scaledHeight() > height) {
                            if (img.getDpiX() > 0 && img.getDpiY() > 0) {
                                float adjx = width / img.scaledWidth();
                                float adjy = height / img.scaledHeight();
                                float adj = Math.min(adjx, adjy);
                                img.scalePercent(7200f / img.getDpiX() * adj, 7200f / img.getDpiY() * adj);
                            }
                            else
                                img.scaleToFit(width, height);
                    }
                    img.setAbsolutePosition(20, 20);
                        document.newPage();
                        document.add(new Paragraph(tiff_file + " - page " + (c + 1)));
                  }
                    cb.addImage(img);
                    System.out.println("Finished page " + (c + 1));
                }
            }
            ra.close();
            document.close();
    } catch (Exception e) {
          JOptionPane.showMessageDialog(internalFrame,
                e.getMessage(),
                e.getClass().getName(),
                JOptionPane.ERROR_MESSAGE);
View Full Code Here

   * @see com.lowagie.tools.AbstractTool#execute()
   */
  public void execute() {
    try {
            String line = null;
            Document document;
            Font f;
            Rectangle pagesize = (Rectangle)getValue("pagesize");
            if ("LANDSCAPE".equals(getValue("orientation"))) {
                f = FontFactory.getFont(FontFactory.COURIER, 10);
                document = new Document(pagesize.rotate(), 36, 9, 36, 36);
            }
            else {
                f = FontFactory.getFont(FontFactory.COURIER, 11);
                document = new Document(pagesize, 72, 36, 36, 36);
            }
            BufferedReader in = new BufferedReader(new FileReader((File)getValue("srcfile")));
            PdfWriter.getInstance(document, new FileOutputStream((File)getValue("destfile")));
            document.open();
            while ((line = in.readLine()) != null) {
                document.add(new Paragraph(12, line, f));
            }
            document.close();
    } catch (Exception e) {
          JOptionPane.showMessageDialog(internalFrame,
                e.getMessage(),
                e.getClass().getName(),
                JOptionPane.ERROR_MESSAGE);
View Full Code Here

      // we retrieve the total number of pages
      int n = reader.getNumberOfPages();
      System.out.println("There are " + n + " pages in the original file.");

      // step 1: creation of a document-object
      Document document = new Document(PageSize.A4);
      // step 2: we create a writer that listens to the document
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
      // step 3: we open the document
      document.open();
      PdfContentByte cb = writer.getDirectContent();
      PdfImportedPage page;
      int rotation;
      int i = 0;
      int p = 0;
      // step 4: we add content
      while (i < n) {
        i++;
        Rectangle rect = reader.getPageSizeWithRotation(i);
        float factorx = (x2 - x1) / rect.width();
        float factory = (y1[p] - y2[p]) / rect.height();
        float factor = (factorx < factory ? factorx : factory);
        float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.width() * factor) / 2f);
        float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.height() * factor) / 2f);
        page = writer.getImportedPage(reader, i);
        rotation = reader.getPageRotation(i);
        if (rotation == 90 || rotation == 270) {
          cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.height() * factor);
        }
        else {
          cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
        }
        cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
        cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
        for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
          cb.moveTo(x3, l);
          cb.lineTo(x4, l);
        }
        cb.rectangle(x1 + dx, y2[p] + dy, rect.width() * factor, rect.height() * factor);
        cb.stroke();
        System.out.println("Processed page " + i);
        p++;
        if (p == pages) {
          p = 0;
          document.newPage();
        }
      }
      // step 5: we close the document
      document.close();
    }
    catch(Exception e) {
          JOptionPane.showMessageDialog(internalFrame,
                e.getMessage(),
                e.getClass().getName(),
View Full Code Here

      PdfReader reader = new PdfReader(src.getAbsolutePath());
      System.out.println("The original file had " + reader.getNumberOfPages() + " pages.");
      reader.selectPages(selection);
      int pages = reader.getNumberOfPages();
      System.err.println("The new file has " + pages + " pages.");
      Document document = new Document(reader.getPageSizeWithRotation(1));
      PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest.getAbsolutePath()));
      document.open();
            PdfImportedPage page;
            for (int i = 0; i < pages; ) {
                ++i;
                System.out.println("Processed page " + i);
                page = copy.getImportedPage(reader, i);
                copy.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
      if (form != null)
                copy.copyAcroForm(reader);
      document.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
View Full Code Here

      if (getValue("srcdir") == null) throw new InstantiationException("You need to choose a source directory");
      File directory = (File)getValue("srcdir");
      if (directory.isFile()) directory = directory.getParentFile();
      if (getValue("destfile") == null) throw new InstantiationException("You need to choose a destination file");
      File pdf_file = (File)getValue("destfile");
      Document document = new Document();
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file));
      writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
      PdfPageLabels pageLabels = new PdfPageLabels();
      int dpiX, dpiY;
      float imgWidthPica, imgHeightPica;
      TreeSet images = new TreeSet();
      File[] files = directory.listFiles();
      if (files == null)
        throw new NullPointerException("listFiles() returns null");
      for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) images.add(files[i]);
      }
      File image;
      String label;
            for (Iterator i = images.iterator(); i.hasNext(); ) {
              image = (File) i.next();
              System.out.println("Testing image: " + image.getName());
              try {
                Image img = Image.getInstance(image.getAbsolutePath());
                dpiX=img.getDpiX();
                    if (dpiX == 0) dpiX=72;
                    dpiY=img.getDpiY();
                    if (dpiY == 0) dpiY=72;
                    imgWidthPica=(72*img.plainWidth()) / dpiX;
                    imgHeightPica=(72*img.plainHeight()) / dpiY;
                    img.scaleAbsolute(imgWidthPica,imgHeightPica);
                    document.setPageSize(new Rectangle(imgWidthPica, imgHeightPica));
                  if (document.isOpen()) {
                    document.newPage();
                  }
                  else {
                    document.open();
                  }
                  img.setAbsolutePosition(0, 0);
                    document.add(img);
                    label = image.getName();
                    if (label.lastIndexOf('.') > 0)
                      label = label.substring(0, label.lastIndexOf('.'));
                    pageLabels.addPageLabel(writer.getPageNumber(), PdfPageLabels.EMPTY, label);
                    System.out.println("Added image: " + image.getName());
                }
              catch(Exception e) {
                System.err.println(e.getMessage());
              }
            }
          if (document.isOpen()) {
            writer.setPageLabels(pageLabels);
              document.close();
          }
          else {
            System.err.println("No images were found in directory " + directory.getAbsolutePath());
          }
    } catch (Exception e) {
View Full Code Here

                                                  Map<String, Font> colorMap) {
        Font roomEvent = FontFactory
            .getFont(FontFactory.HELVETICA, 12f, Font.ITALIC, new Color(0xFF, 0x00, 0xFF));

        try {
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            writer.setPageEvent(new PDFEventListener());
            document.open();


            Paragraph p = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.title", "monitoring"),
                FontFactory.getFont(FontFactory.HELVETICA,
                    18, Font.BOLD));
            document.add(p);
            document.add(Chunk.NEWLINE);

            ConversationInfo coninfo = new ConversationUtils()
                .getConversationInfo(conversation.getConversationID(), false);

            String participantsDetail;
            if (coninfo.getAllParticipants() == null) {
                participantsDetail = coninfo.getParticipant1() + ", " + coninfo.getParticipant2();
            }
            else {
                participantsDetail = String.valueOf(coninfo.getAllParticipants().length);
            }

            Paragraph chapterTitle = new Paragraph(
                LocaleUtils
                    .getLocalizedString("archive.search.pdf.participants", "monitoring") +
                    " " + participantsDetail,
                FontFactory.getFont(FontFactory.HELVETICA, 12,
                    Font.BOLD));

            document.add(chapterTitle);


            Paragraph startDate = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.startdate", "monitoring") +
                    " " +
                    coninfo.getDate(),
                FontFactory.getFont(FontFactory.HELVETICA, 12,
                    Font.BOLD));
            document.add(startDate);


            Paragraph duration = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.duration", "monitoring") +
                    " " +
                    coninfo.getDuration(),
                FontFactory.getFont(FontFactory.HELVETICA, 12,
                    Font.BOLD));
            document.add(duration);


            Paragraph messageCount = new Paragraph(
                LocaleUtils
                    .getLocalizedString("archive.search.pdf.messagecount", "monitoring") +
                    " " +
                    conversation.getMessageCount(),
                FontFactory.getFont(FontFactory.HELVETICA, 12,
                    Font.BOLD));
            document.add(messageCount);
            document.add(Chunk.NEWLINE);


            Paragraph messageParagraph;

            for (ArchivedMessage message : conversation.getMessages()) {
                String time = JiveGlobals.formatTime(message.getSentDate());
                String from = message.getFromJID().getNode();
                if (conversation.getRoom() != null) {
                    from = message.getToJID().getResource();
                }
                String body = message.getBody();
                String prefix;
                if (!message.isRoomEvent()) {
                    prefix = "[" + time + "] " + from + ":  ";
                    Font font = colorMap.get(message.getFromJID().toString());
                    if (font == null) {
                        font = colorMap.get(message.getFromJID().toBareJID());
                    }
                    if (font == null) {
                        font = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.BOLD, Color.BLACK);
                    }
                    messageParagraph = new Paragraph(new Chunk(prefix, font));
                }
                else {
                    prefix = "[" + time + "] ";
                    messageParagraph = new Paragraph(new Chunk(prefix, roomEvent));
                }
                messageParagraph.add(body);
                messageParagraph.add(" ");
                document.add(messageParagraph);
            }

            document.close();
            return baos;
        }
        catch (DocumentException e) {
            Log.error("error creating PDF document: " + e.getMessage(), e);
            return null;
View Full Code Here

     * @param inputCommand
     * @throws Exception
     */
    private void executeBurst(SplitParsedCommand inputCommand) throws Exception {
        int currentPage;
        Document currentDocument;
        pdfReader = new PdfReader(new RandomAccessFileOrArray(inputCommand.getInputFile().getFile().getAbsolutePath()),
                inputCommand.getInputFile().getPasswordBytes());
        pdfReader.removeUnusedObjects();
        pdfReader.consolidateNamedDestinations();

        // we retrieve the total number of pages
        int n = pdfReader.getNumberOfPages();
        int fileNum = 0;
        LOG.info("Found " + n + " pages in input pdf document.");
        for (currentPage = 1; currentPage <= n; currentPage++) {
            LOG.debug("Creating a new document.");
            fileNum++;
            File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, null);
            File outFile = new File(inputCommand.getOutputFile().getCanonicalPath(), prefixParser
                    .generateFileName(request));
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));

            pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));

            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);
            setCompressionSettingOnWriter(inputCommand, pdfWriter);

            // set pdf version
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
            PdfImportedPage importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
            pdfWriter.addPage(importedPage);
            currentDocument.close();
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
            setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
        }
        pdfReader.close();
View Full Code Here

        // we retrieve the total number of pages
        int n = pdfReader.getNumberOfPages();
        int fileNum = 0;
        LOG.info("Found " + n + " pages in input pdf document.");
        int currentPage;
        Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
        boolean isTimeToClose = false;
        PdfImportedPage importedPage;
        File tmpFile = null;
        File outFile = null;
        for (currentPage = 1; currentPage <= n; currentPage++) {
            // check if i've to read one more page or to open a new doc
            isTimeToClose = ((currentPage != 1) && ((SplitParsedCommand.S_ODD.equals(inputCommand.getSplitType()) && ((currentPage % 2) != 0)) || (SplitParsedCommand.S_EVEN
                    .equals(inputCommand.getSplitType()) && ((currentPage % 2) == 0))));

            if (!isTimeToClose) {
                LOG.debug("Creating a new document.");
                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));

                pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));
                // 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 ((isTimeToClose) || (currentPage == n)
                    || ((currentPage == 1) && (SplitParsedCommand.S_ODD.equals(inputCommand.getSplitType())))) {
                currentDocument.close();
                FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
                LOG.debug("File " + outFile.getCanonicalPath() + " created.");
            }
            setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
        }
View Full Code Here

            throw new SplitException(SplitException.ERR_NO_PAGE_LIMITS);
        }

        // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START BOOKMARKS
        int currentPage;
        Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
        int relativeCurrentPage = 0;
        int endPage = n;
        int startPage = 1;
        PdfImportedPage importedPage;
        File tmpFile = null;
        File outFile = null;

        Iterator itr = limitsList.iterator();
        if (itr.hasNext()) {
            endPage = ((Integer) itr.next()).intValue();
        }
        for (currentPage = 1; currentPage <= n; currentPage++) {
            relativeCurrentPage++;
            // check if i've to read one more page or to open a new doc
            if (relativeCurrentPage == 1) {
                LOG.debug("Creating a new document.");
                fileNum++;
                tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
                String bookmark = null;
                if (bookmarksTable != null && bookmarksTable.size() > 0) {
                    bookmark = (String) bookmarksTable.get(new Integer(currentPage));
                }
                FileNameRequest request = new FileNameRequest(currentPage, fileNum, bookmark);
                outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
                startPage = currentPage;
                currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));

                pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));

                // 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 == endPage) {
                LOG.info("Temporary document " + tmpFile.getName() + " done, now adding bookmarks...");
                // manage bookmarks
                List bookmarks = bookmarkProcessor.processBookmarks(startPage, endPage);
                if (bookmarks != null) {
                    pdfWriter.setOutlines(bookmarks);
                }
                relativeCurrentPage = 0;
                currentDocument.close();
                FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
                LOG.debug("File " + outFile.getCanonicalPath() + " created.");
                endPage = (itr.hasNext()) ? ((Integer) itr.next()).intValue() : n;
            }
            setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
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.