Example usage for com.lowagie.text.pdf RandomAccessFileOrArray RandomAccessFileOrArray

List of usage examples for com.lowagie.text.pdf RandomAccessFileOrArray RandomAccessFileOrArray

Introduction

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

Prototype

public RandomAccessFileOrArray(RandomAccessFileOrArray file) 

Source Link

Usage

From source file:AppletViewer.java

License:Open Source License

/**
 * Metodo que crea un PDF a partir del archivo TIF con sus anotaciones
 * @param docid/* ww w.j  av a 2 s . c  om*/
 */
public void convertDocument(String docid) {
    try {
        File dir = new File(descargados);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        dir = new File(transferencias);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // CARGAR TIF CON ANOTACIONES
        String tmpFileName = "TMP" + String.valueOf(System.currentTimeMillis()) + ".tif";
        OutputStream output = new FileOutputStream(descargados + File.separator + tmpFileName);
        myGenDocViewer.exportDocument(output, true, false, "image/tiff");
        output.close();

        // CONVERTIR TIF A PDF
        RandomAccessFileOrArray myTiffFile = new RandomAccessFileOrArray(
                descargados + File.separator + tmpFileName);
        int numberOfPages = TiffImage.getNumberOfPages(myTiffFile);
        Document TifftoPDF = new Document();
        TifftoPDF.setMargins(0, 0, 0, 0);
        PdfWriter.getInstance(TifftoPDF,
                new FileOutputStream(transferencias + File.separator + type + "-AN.pdf"));
        TifftoPDF.open();
        for (int i = 1; i <= numberOfPages; i++) {
            Image tempImage = TiffImage.getTiffImage(myTiffFile, i);
            float dpiX = tempImage.getDpiX() == 0 ? 200 : tempImage.getDpiX();
            float dpiY = tempImage.getDpiY() == 0 ? 200 : tempImage.getDpiY();
            float factorX = 72 / dpiX;
            float factorY = 72 / dpiY;
            tempImage.scaleAbsolute(factorX * tempImage.getWidth(), factorY * tempImage.getHeight());
            TifftoPDF.add(tempImage);
        }
        myTiffFile.close();
        TifftoPDF.close();

        // BORRAR EL TIFF
        File file = new File(descargados + File.separator + tmpFileName);
        if (file.delete()) {
            System.out.println(file.getName() + " eliminado");
        } else {
            file.deleteOnExit();
            ;
            System.out.println("Eliminacion fallo");
        }

        System.out.println("Fin de la creacion del PDF con anotaciones");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.geek.tutorial.itext.image.SimpleImages.java

License:Open Source License

public SimpleImages() throws Exception {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("SimpleImages.pdf"));
    document.open();// w  ww  .j a  v  a 2  s  .  co m

    // Code 1
    document.add(new Paragraph("Simple Image"));
    com.lowagie.text.Image image = com.lowagie.text.Image.getInstance("mouse.jpg");
    document.add(image);

    // Code 2
    document.add(new Paragraph("\n" + "AWT Image"));
    java.awt.Image awtImg = java.awt.Toolkit.getDefaultToolkit().createImage("square.jpg");
    com.lowagie.text.Image image2 = com.lowagie.text.Image.getInstance(awtImg, null);
    document.add(image2);
    document.newPage();

    // Code 3
    document.add(new Paragraph("Multipages tiff file"));
    RandomAccessFileOrArray ra = new RandomAccessFileOrArray("multipage.tif");
    int pages = TiffImage.getNumberOfPages(ra);
    for (int i = 1; i <= pages; i++) {
        document.add(TiffImage.getTiffImage(ra, i));
    }
    document.newPage();

    // Code 4
    document.add(new Paragraph("Animated Gifs"));
    GifImage img = new GifImage("bee.gif");
    int frame_count = img.getFrameCount();
    for (int i = 1; i <= frame_count; i++) {
        document.add(img.getImage(i));
    }
    document.close();
}

From source file:com.ikon.util.DocConverter.java

License:Open Source License

/**
 * TIFF to PDF conversion/*from   w  w  w.  j a  va2 s .c om*/
 */
public void tiff2pdf(File input, File output) throws ConversionException {
    RandomAccessFileOrArray ra = null;
    Document doc = null;

    try {
        // Open PDF
        doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
        PdfContentByte cb = writer.getDirectContent();
        doc.open();
        //int pages = 0;

        // Open TIFF
        ra = new RandomAccessFileOrArray(input.getPath());
        int comps = TiffImage.getNumberOfPages(ra);

        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);

            if (img != null) {
                log.debug("tiff2pdf - page {}", c + 1);

                if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                    img.scaleToFit(500, 700);
                }

                img.setAbsolutePosition(20, 20);
                //doc.add(new Paragraph("page " + (c + 1)));
                cb.addImage(img);
                doc.newPage();
                //++pages;
            }
        }
    } catch (FileNotFoundException e) {
        throw new ConversionException("File not found: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Document exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ConversionException("IO exception: " + e.getMessage(), e);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (doc != null) {
            doc.close();
        }
    }
}

From source file:com.openkm.util.DocConverter.java

License:Open Source License

/**
 * TIFF to PDF conversion/*from   w w  w.jav a2 s .c o m*/
 */
public void tiff2pdf(File input, File output) throws ConversionException {
    RandomAccessFileOrArray ra = null;
    Document doc = null;

    try {
        // Open PDF
        doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
        PdfContentByte cb = writer.getDirectContent();
        doc.open();
        // int pages = 0;

        // Open TIFF
        ra = new RandomAccessFileOrArray(input.getPath());
        int comps = TiffImage.getNumberOfPages(ra);

        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);

            if (img != null) {
                log.debug("tiff2pdf - page {}", c + 1);

                if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                    img.scaleToFit(500, 700);
                }

                img.setAbsolutePosition(20, 20);
                // doc.add(new Paragraph("page " + (c + 1)));
                cb.addImage(img);
                doc.newPage();
                // ++pages;
            }
        }
    } catch (FileNotFoundException e) {
        throw new ConversionException("File not found: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Document exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ConversionException("IO exception: " + e.getMessage(), e);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (doc != null) {
            doc.close();
        }
    }
}

From source file:convert.Convertings.java

public void convertTif2PDF(String tifPath, String path) {
    System.out.println("one");
    String arg[] = { tifPath };//w w w .j  a  v a 2 s.  co m
    System.out.println("one2");
    if (arg.length < 1) {
        System.out.println("Usage: Tiff2Pdf file1.tif [file2.tif ... fileN.tif]");
        System.exit(1);
    }
    String tiff;
    String pdf;
    System.out.println("two");
    for (int i = 0; i < arg.length; i++) {
        tiff = arg[i];
        pdf = path + ".pdf";
        Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
            int pages = 0;
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            RandomAccessFileOrArray ra = null;
            int comps = 0;
            try {
                ra = new RandomAccessFileOrArray(tiff);
                comps = TiffImage.getNumberOfPages(ra);
            } catch (Throwable e) {
                System.out.println("Exception in " + tiff + " " + e.getMessage());
                continue;
            }
            System.out.println("Processing: " + tiff);
            for (int c = 0; c < comps; ++c) {
                try {
                    Image img = TiffImage.getTiffImage(ra, c + 1);
                    if (img != null) {
                        System.out.println("page " + (c + 1));
                        System.out.println("img.getDpiX() : " + img.getDpiX());
                        System.out.println("img.getDpiY() : " + img.getDpiY());
                        img.scalePercent(6200f / img.getDpiX(), 6200f / img.getDpiY());
                        //img.scalePercent(img.getDpiX(), img.getDpiY());
                        //document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
                        img.setAbsolutePosition(0, 0);
                        cb.addImage(img);
                        document.newPage();
                        ++pages;
                    }
                } catch (Throwable e) {
                    System.out.println("Exception " + tiff + " page " + (c + 1) + " " + e.getMessage());
                }
            }
            ra.close();
            document.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("done");
    }
}

From source file:it.jugpadova.blo.ParticipantBadgeBo.java

License:Apache License

/**
 * Build a PDF with the badges of confirmed participants.
 *///from   ww  w.ja  v  a2s . c o  m
public byte[] buildPDFBadges(Event event) throws IOException, DocumentException {
    List<Participant> participants = participantDao
            .findConfirmedParticipantsByEventIdOrderByLastNameAndFirstName(event.getId());
    int participantsPerPage = getParticipantsPerPage(event);
    int pages = (participants.size() / participantsPerPage) + 2; // prints a more page with empty badges
    ByteArrayOutputStream pdfMergedBaos = new ByteArrayOutputStream();
    PdfCopyFields pdfMerged = new PdfCopyFields(pdfMergedBaos);
    int newIndex = 1;
    for (int i = 0; i < pages; i++) {
        InputStream templateIs = getBadgePageTemplateInputStream(event);
        RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs);
        PdfReader template = new PdfReader(rafa, null);
        ByteArrayOutputStream pdfPageBaos = new ByteArrayOutputStream();
        PdfStamper pdfPage = new PdfStamper(template, pdfPageBaos);
        AcroFields pdfPageForm = pdfPage.getAcroFields();
        for (int j = 1; j <= participantsPerPage; j++) {
            pdfPageForm.renameField("title" + j, "title" + newIndex);
            pdfPageForm.renameField("firstName" + j, "firstName" + newIndex);
            pdfPageForm.renameField("lastName" + j, "lastName" + newIndex);
            pdfPageForm.renameField("firm" + j, "firm" + newIndex);
            pdfPageForm.renameField("role" + j, "role" + newIndex);
            newIndex++;
        }
        pdfPage.close();
        template.close();
        pdfMerged.addDocument(new PdfReader(pdfPageBaos.toByteArray()));
    }
    pdfMerged.close();
    ByteArrayOutputStream resultBaos = new ByteArrayOutputStream();
    PdfReader mergedReader = new PdfReader(pdfMergedBaos.toByteArray());
    PdfStamper mergedStamper = new PdfStamper(mergedReader, resultBaos);
    AcroFields mergedForm = mergedStamper.getAcroFields();
    int count = 1;
    for (int i = 0; i < pages; i++) {
        for (int j = 1; j <= participantsPerPage; j++) {
            mergedForm.setField("title" + count, event.getTitle());
            count++;
        }
    }
    count = 1;
    for (Participant participant : participants) {
        mergedForm.setField("firstName" + count, participant.getFirstName());
        mergedForm.setField("lastName" + count, participant.getLastName());
        count++;
    }
    mergedStamper.setFormFlattening(true);
    mergedStamper.close();
    return resultBaos.toByteArray();
}

From source file:it.jugpadova.blo.ParticipantBadgeBo.java

License:Apache License

protected int getParticipantsPerPage(Event event) throws IOException {
    int count = 0;
    InputStream templateIs = getBadgePageTemplateInputStream(event);
    RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs);
    PdfReader template = new PdfReader(rafa, null);
    AcroFields form = template.getAcroFields();
    HashMap fields = form.getFields();
    while (true) {
        if (fields.containsKey("firstName" + (count + 1))) {
            count++;//from   w ww  .j  a  va  2s.  co  m
        } else {
            break;
        }
    }
    template.close();
    return count;
}

From source file:it.pdfsam.console.tools.pdf.PdfAlternateMix.java

License:Open Source License

/**
  * Execute the mix command. On error an exception is thrown.
  * @throws AlternateMixException/*from   w  ww  .  j a v a  2s .c  o m*/
  */
public void execute() throws AlternateMixException {
    try {
        workingIndeterminate();
        out_message = "";
        Document pdf_document = null;
        PdfCopy pdf_writer = null;
        File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent());
        PdfReader pdf_reader1;
        PdfReader pdf_reader2;

        pdf_reader1 = new PdfReader(new RandomAccessFileOrArray(input_file1.getAbsolutePath()), null);
        pdf_reader1.consolidateNamedDestinations();
        limits1[1] = pdf_reader1.getNumberOfPages();

        pdf_reader2 = new PdfReader(new RandomAccessFileOrArray(input_file2.getAbsolutePath()), null);
        pdf_reader2.consolidateNamedDestinations();
        limits2[1] = pdf_reader2.getNumberOfPages();

        pdf_document = new Document(pdf_reader1.getPageSizeWithRotation(1));
        pdf_writer = new PdfCopy(pdf_document, new FileOutputStream(tmp_o_file));
        if (compressed_boolean) {
            pdf_writer.setFullCompression();
        }
        out_message += LogFormatter.formatMessage("Temporary file created-\n");
        MainConsole.setDocumentCreator(pdf_document);
        pdf_document.open();

        PdfImportedPage page;
        //importo
        boolean finished1 = false;
        boolean finished2 = false;
        int current1 = (reverseFirst) ? limits1[1] : limits1[0];
        int current2 = (reverseSecond) ? limits2[1] : limits2[0];
        while (!finished1 || !finished2) {
            if (!finished1) {
                if (current1 >= limits1[0] && current1 <= limits1[1]) {
                    page = pdf_writer.getImportedPage(pdf_reader1, current1);
                    pdf_writer.addPage(page);
                    current1 = (reverseFirst) ? (current1 - 1) : (current1 + 1);
                } else {
                    out_message += LogFormatter.formatMessage("First file processed-\n");
                    finished1 = true;
                }
            }
            if (!finished2) {
                if (current2 >= limits2[0] && current2 <= limits2[1] && !finished2) {
                    page = pdf_writer.getImportedPage(pdf_reader2, current2);
                    pdf_writer.addPage(page);
                    current2 = (reverseSecond) ? (current2 - 1) : (current2 + 1);
                } else {
                    out_message += LogFormatter.formatMessage("Second file processed-\n");
                    finished2 = true;
                }
            }

        }

        pdf_reader1.close();
        pdf_writer.freeReader(pdf_reader1);
        pdf_reader2.close();
        pdf_writer.freeReader(pdf_reader2);

        pdf_document.close();
        // step 6: temporary buffer moved to output file
        renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean);
        out_message += LogFormatter.formatMessage("Alternate mix completed-\n");

    } catch (Exception e) {
        throw new AlternateMixException(e);
    } finally {
        workCompleted();
    }
}

From source file:it.pdfsam.console.tools.pdf.PdfConcat.java

License:Open Source License

/**
 * Execute the concat command. On error an exception is thrown.
 * @throws ConcatException/* w  w  w.j av a  2 s . c o  m*/
 */
public void execute() throws ConcatException {
    try {
        percentageChanged(0, 0);
        out_message = "";
        String file_name;
        int pageOffset = 0;
        ArrayList master = new ArrayList();
        int f = 0;
        Document pdf_document = null;
        PdfConcatenator pdf_writer = null;
        int total_processed_pages = 0;
        String[] page_selection = u_string.split(":");
        File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent());
        PdfReader pdf_reader;
        for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) {
            String current_p_selection;
            //get page selection. If arrayoutofbounds default behaviour is "all" 
            try {
                current_p_selection = page_selection[f].toLowerCase();
                if (current_p_selection.equals(""))
                    current_p_selection = "all";
            } catch (Exception e) {
                current_p_selection = "all";
            }
            //validation
            if (!(Pattern.compile("([0-9]+[-][0-9]+)|(all)", Pattern.CASE_INSENSITIVE)
                    .matcher(current_p_selection).matches())) {
                String errorMsg = "";
                try {
                    tmp_o_file.delete();
                } catch (Exception e) {
                    errorMsg = " Unable to delete temporary file.";
                }
                throw new ConcatException(
                        "ValidationError: Syntax error on " + current_p_selection + "." + errorMsg);
            }
            file_name = f_list_itr.next().toString();
            //reader creation
            pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_name), null);
            pdf_reader.consolidateNamedDestinations();
            int pdf_number_of_pages = pdf_reader.getNumberOfPages();
            //default behaviour
            int start = 0;
            int end_page = pdf_number_of_pages;
            if (!(current_p_selection.equals("all"))) {
                boolean valid = true;
                String exceptionMsg = "";
                String[] limits = current_p_selection.split("-");
                try {
                    start = Integer.parseInt(limits[0]);
                    end_page = Integer.parseInt(limits[1]);
                } catch (Exception ex) {
                    valid = false;
                    exceptionMsg += "ValidationError: Syntax error on " + current_p_selection + ".";
                    try {
                        tmp_o_file.delete();
                    } catch (Exception e) {
                        exceptionMsg += " Unable to delete temporary file.";
                    }
                }
                if (valid) {
                    //validation
                    if (start < 0) {
                        valid = false;
                        exceptionMsg = "ValidationError: Syntax error. " + (start) + " must be positive in "
                                + current_p_selection + ".";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    } else if (end_page > pdf_number_of_pages) {
                        valid = false;
                        exceptionMsg = "ValidationError: Cannot merge at page " + end_page + ". No such page.";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    } else if (start > end_page) {
                        valid = false;
                        exceptionMsg = "ValidationError: Syntax error. " + (start) + " is bigger than "
                                + end_page + " in " + current_p_selection + ".";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    }
                }
                if (!valid) {
                    throw new ConcatException(exceptionMsg);
                }
            }
            List bookmarks = SimpleBookmark.getBookmark(pdf_reader);
            if (bookmarks != null) {
                //if the end page is not the end of the doc, delete bookmarks after it
                if (end_page < pdf_number_of_pages) {
                    SimpleBookmark.eliminatePages(bookmarks, new int[] { end_page + 1, pdf_number_of_pages });
                }
                // if start page isn't the first page of the document, delete bookmarks before it
                if (start > 0) {
                    SimpleBookmark.eliminatePages(bookmarks, new int[] { 1, start });
                    //bookmarks references must be taken back
                    SimpleBookmark.shiftPageNumbers(bookmarks, -start, null);
                }
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += (end_page - start);
            out_message += LogFormatter.formatMessage(file_name + ": " + end_page + " pages-\n");
            if (f == 0) {
                if (copyfields_boolean) {
                    // step 1: we create a writer 
                    pdf_writer = new PdfCopyFieldsConcatenator(new FileOutputStream(tmp_o_file),
                            compressed_boolean);
                    HashMap meta = pdf_reader.getInfo();
                    meta.put("Creator", MainConsole.CREATOR);
                } else {
                    // step 1: creation of a document-object
                    pdf_document = new Document(pdf_reader.getPageSizeWithRotation(1));
                    // step 2: we create a writer that listens to the document
                    pdf_writer = new PdfSimpleConcatenator(pdf_document, new FileOutputStream(tmp_o_file),
                            compressed_boolean);
                    // step 3: we open the document
                    MainConsole.setDocumentCreator(pdf_document);
                    pdf_document.open();
                }
                out_message += LogFormatter.formatMessage("Temporary file created-\n");
            }
            // step 4: we add content
            pdf_reader.selectPages(start + "-" + end_page);
            pdf_writer.addDocument(pdf_reader);
            //fix 03/07
            //pdf_reader = null;
            pdf_reader.close();
            pdf_writer.freeReader(pdf_reader);
            total_processed_pages += end_page - start + 1;
            out_message += LogFormatter.formatMessage((end_page - start) + " pages processed correctly-\n");
            f++;
            try {
                percentageChanged((f * 100) / f_list.size(), (end_page - start));
            } catch (RuntimeException re) {
                out_message += LogFormatter.formatMessage("RuntimeException: " + re.getMessage() + "\n");
            }
        }
        if (master.size() > 0) {
            pdf_writer.setOutlines(master);
        }
        out_message += LogFormatter.formatMessage("Total processed pages: " + total_processed_pages + "-\n");
        // step 5: we close the document
        if (pdf_document != null) {
            pdf_document.close();
        }
        pdf_writer.close();
        // step 6: temporary buffer moved to output file
        renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean);
    } catch (Exception e) {
        throw new ConcatException(e);
    } finally {
        workCompleted();
    }
}

From source file:it.pdfsam.console.tools.pdf.PdfEncrypt.java

License:Open Source License

/**
 * Execute the encrypt command. On error an exception is thrown.
 * @throws EncryptException/*from   ww  w  .j  a va  2  s. c  o  m*/
 */
public void execute() throws EncryptException {
    try {
        workingIndeterminate();
        out_message = "";
        int f = 0;
        for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) {
            String file_name = f_list_itr.next().toString();
            prefixParser = new PrefixParser(prefix_value, new File(file_name).getName());
            File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir.getAbsolutePath());
            out_message += LogFormatter.formatMessage("Temporary file created-\n");
            PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(file_name), null);
            HashMap meta = pdfReader.getInfo();
            meta.put("Creator", MainConsole.CREATOR);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmp_o_file));
            if (compressed_boolean) {
                pdfStamper.setFullCompression();
            }
            pdfStamper.setMoreInfo(meta);
            pdfStamper.setEncryption(etype, u_pwd, a_pwd, user_permissions);
            pdfStamper.close();
            /*PdfEncryptor.encrypt(pdf_reader,new FileOutputStream(tmp_o_file), etype, u_pwd, a_pwd,user_permissions, meta);*/
            File out_file = new File(o_dir, prefixParser.generateFileName());
            renameTemporaryFile(tmp_o_file, out_file, overwrite_boolean);
            f++;
        }
        out_message += LogFormatter.formatMessage("Pdf files encrypted in " + o_dir.getAbsolutePath() + "-\n"
                + PdfEncryptor.getPermissionsVerbose(user_permissions));
    } catch (Exception e) {
        throw new EncryptException(e);
    } finally {
        workCompleted();
    }
}