Example usage for com.lowagie.text Rectangle Rectangle

List of usage examples for com.lowagie.text Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(float urx, float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

Usage

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

public void printImagePdf(String filename, DesignerCanvas canvas, Dimension graphsize) {
    try {//from  ww w .j a v  a  2s  .  c om
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\winnt\\fonts");
        // mapper.insertDirectory("c:\\windows\\fonts");
        // we create a template and a Graphics2D object that corresponds
        // with it
        int margin = 72; // 1 inch
        float scale = 0.5f;
        boolean multiple_page = true;
        Rectangle page_size;
        if (multiple_page) {
            page_size = PageSize.LETTER.rotate();
        } else {
            page_size = new Rectangle((int) (graphsize.getWidth() * scale) + margin,
                    (int) (graphsize.getHeight() * scale) + margin);
        }
        Document document = new Document(page_size);
        DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.setPageSize(page_size);
        int image_w = (int) page_size.getWidth() - margin;
        int image_h = (int) page_size.getHeight() - margin;
        boolean edsave = canvas.editable;
        canvas.editable = false;
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        if (multiple_page) {
            int horizontal_pages = (int) (graphsize.width * scale) / image_w + 1;
            int vertical_pages = (int) (graphsize.height * scale) / image_h + 1;
            for (int i = 0; i < horizontal_pages; i++) {
                for (int j = 0; j < vertical_pages; j++) {
                    Image img;
                    PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
                    PdfTemplate tp = cb.createTemplate(image_w, image_h);
                    Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
                    tp.setWidth(image_w);
                    tp.setHeight(image_h);
                    g2.scale(scale, scale);
                    g2.translate(-i * image_w / scale, -j * image_h / scale);
                    canvas.paintComponent(g2);
                    g2.dispose();
                    img = new ImgTemplate(tp);
                    document.add(img);
                }
            }
        } else {
            Image img;
            PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
            PdfTemplate tp = cb.createTemplate(image_w, image_h);
            Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
            tp.setWidth(image_w);
            tp.setHeight(image_h);
            g2.scale(scale, scale);
            canvas.paintComponent(g2);
            g2.dispose();
            img = new ImgTemplate(tp);
            document.add(img);
        }
        canvas.setBackground(bgsave);
        canvas.editable = edsave;
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.compomics.mascotdatfile.research.tool.spectrumviewer.spectrumviewer_gui.Spectrumviewer_gui.java

License:Apache License

/**
 * This method is called whenever the user clicked the button to export the spectrum to pdf.
 *///from  www .  java  2 s.  c  om
private void pdfOutputTriggered() {
    if (dtp != null) {

        // Looping boolean.
        boolean lbContinue = true;
        // Previous selected path.
        String previousPath = "/";
        // The file filter to use.
        FileFilter filter = new FileFilter() {
            public boolean accept(File f) {
                boolean result = false;
                if (f.isDirectory() || f.getName().endsWith(".pdf")) {
                    result = true;
                }
                return result;
            }

            public String getDescription() {
                return "PDF file";
            }
        };
        while (lbContinue) {
            JFileChooser jfc = new JFileChooser(previousPath);
            jfc.setDialogTitle("Save spectrum panel as PDF file");
            jfc.setDialogType(JFileChooser.SAVE_DIALOG);
            jfc.setFileFilter(filter);
            int returnVal = jfc.showSaveDialog(this.getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = jfc.getSelectedFile();
                // Append the file extension if it is not already there.
                if (jfc.getFileFilter() == filter && !file.getName().toLowerCase().endsWith(".pdf")) {
                    file = new File(file.getAbsolutePath() + ".pdf");
                }
                // Check for existing file.
                if (file.exists()) {
                    int reply = JOptionPane.showConfirmDialog(this.getParent(),
                            new String[] { "File '" + file.getAbsolutePath() + "' exists.",
                                    "Do you wish to overwrite?" },
                            "File exists!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (reply != JOptionPane.YES_OPTION) {
                        previousPath = file.getParent();
                        continue;
                    }
                }

                // Output to PDF.
                JPanel jpanSpectrum = dtp.getSpectrumPanel();
                float lWidthFloat = (new Double(jpanSpectrum.getSize().getWidth())).floatValue() + 20;
                float lHeightFloat = (new Double(jpanSpectrum.getSize().getHeight())).floatValue();
                int lWidthInt = (new Double(jpanSpectrum.getSize().getWidth())).intValue();
                int lHeightInt = (new Double(jpanSpectrum.getSize().getHeight())).intValue();

                Document document = new Document(new Rectangle(lWidthInt, lHeightInt));

                try {
                    PdfWriter writer;
                    writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                    document.open();
                    PdfContentByte cb = writer.getDirectContent();
                    PdfTemplate tp = cb.createTemplate(lWidthFloat, lHeightFloat);
                    Graphics2D g2;
                    g2 = tp.createGraphicsShapes(lWidthFloat, lHeightFloat);
                    jpanSpectrum.print(g2);
                    g2.dispose();
                    cb.addTemplate(tp, 0, 0);
                    writer.flush();
                    JOptionPane.showMessageDialog(this, "Data successfully written to '" + file + "'!",
                            "Output completed!", JOptionPane.INFORMATION_MESSAGE);
                    document.close();
                } catch (DocumentException e) {
                    JOptionPane.showMessageDialog(this,
                            new String[] { "Unable to create PDF file!", e.getMessage() },
                            "Unable to create PDF file!", JOptionPane.WARNING_MESSAGE);
                } catch (FileNotFoundException e) {
                    // Should never occur.
                    JOptionPane.showMessageDialog(this,
                            new String[] { "Unable to write file!", e.getMessage() }, "Unable to write file!",
                            JOptionPane.WARNING_MESSAGE);
                }

                lbContinue = false;
            } else {
                lbContinue = false;
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "You need to load a datfile and SpectrumPanel first!",
                "No datfile loaded yet!", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:com.compomics.pepshell.controllers.dataexport.PDFExport.java

License:Apache License

@Override
public void exportImage(BufferedImage imageToExport, String filename) {
    File exportFile = new File(ProgramVariables.EXPORTFOLDER, filename + ".pdf");
    if (append && exportFile.exists()) {

    } else {/*ww w .ja v  a 2s .  c o  m*/
        File exportImageFile = new File(System.getProperty("file.temp"), filename);
        try {
            ImageIO.write(imageToExport, "png", new FileOutputStream(exportImageFile));
            Image pdfImage = Image.getInstance(exportImageFile.getAbsolutePath());
            Document document = new Document(new Rectangle(pdfImage.absoluteX(), pdfImage.absoluteY()));
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(exportFile));
            document.open();
            document.newPage();
            document.add(pdfImage);
            document.close();
        } catch (DocumentException | IOException ex) {
            FaultBarrier.getInstance().handleException(ex);
        }
    }
}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java

License:Open Source License

public static boolean exportToFile(WikiPDFContext context, Connection db) throws Exception {

    LOG.debug("exportToFile-> begin");

    // Context Objects
    Wiki wiki = context.getWiki();/*from  w w  w  .  j ava2  s .co m*/
    Project project = context.getProject();
    File file = context.getFile();
    WikiExportBean exportBean = context.getExportBean();

    // Determine the content to parse
    String content = wiki.getContent();
    if (content == null) {
        return false;
    }

    // Create a pdf
    Document document = new Document(PageSize.LETTER);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

    // Meta data
    document.addTitle(project.getTitle());
    document.addSubject(wiki.getSubject());
    document.addCreator("Concursive ConcourseConnect");
    document.addAuthor("Wiki Contributor");
    //writer.setPageEvent(new PageNumbersWatermark());

    if (!exportBean.getIncludeTitle()) {
        boolean hasTitle = StringUtils.hasText(wiki.getSubject());
        HeaderFooter pageFooter = new HeaderFooter(
                new Phrase(project.getTitle() + (hasTitle ? ": " + wiki.getSubject() : "") + " - page "),
                new Phrase(""));
        pageFooter.setAlignment(Element.ALIGN_CENTER);
        document.setFooter(pageFooter);
    }

    document.open();

    if (exportBean.getIncludeTitle()) {
        //HeaderFooter pageHeader = new HeaderFooter(new Phrase(project.getTitle()), false);
        //document.setHeader(pageHeader);
        boolean hasTitle = (StringUtils.hasText(wiki.getSubject()));
        HeaderFooter pageFooter = new HeaderFooter(
                new Phrase(project.getTitle() + (hasTitle ? ": " + wiki.getSubject() : "") + " - page "),
                new Phrase(""));
        pageFooter.setAlignment(Element.ALIGN_CENTER);
        document.setFooter(pageFooter);

        // Draw a title page
        Rectangle rectangle = new Rectangle(600, 30);
        rectangle.setBackgroundColor(new Color(100, 100, 100));
        LOG.debug("document.add(rectangle)");
        document.add(rectangle);

        document.add(new Paragraph(project.getTitle(), titleFont));
        if (!"".equals(wiki.getSubject())) {
            document.add(new Paragraph(wiki.getSubject(), titleFont));
        }
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Last Modified: " + wiki.getModified(), titleSmallFont));
        document.newPage();
    }

    ArrayList<Integer> wikiListDone = new ArrayList<Integer>();

    appendWiki(context, context.getWiki(), document, db, wikiListDone);
    // Close everything
    document.close();
    writer.close();
    LOG.debug("exportToFile-> finished");
    return true;
}

From source file:com.develog.utils.report.engine.export.JRPdfExporter.java

License:Open Source License

/**
 *
 *///w  ww .  jav  a2s  .  co m
protected void exportReportToStream(OutputStream os) throws JRException {
    //ByteArrayOutputStream baos = new ByteArrayOutputStream();

    document = new Document(new Rectangle(jasperPrint.getPageWidth(), jasperPrint.getPageHeight()));

    imageTesterDocument = new Document(new Rectangle(10, //jasperPrint.getPageWidth(),
            10 //jasperPrint.getPageHeight()
    ));

    try {
        PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
        pdfWriter.setCloseStream(false);

        if (isEncrypted) {
            pdfWriter.setEncryption(is128BitKey, userPassword, ownerPassword, permissions);
        }

        document.open();

        PdfWriter imageTesterPdfWriter = PdfWriter.getInstance(imageTesterDocument,
                new ByteArrayOutputStream());
        imageTesterDocument.open();
        imageTesterDocument.newPage();
        imageTesterPdfContentByte = imageTesterPdfWriter.getDirectContent();
        imageTesterPdfContentByte.setLiteral("\n");

        List pages = jasperPrint.getPages();
        if (pages != null && pages.size() > 0) {
            Chunk chunk = null;
            ColumnText colText = null;
            JRPrintPage page = null;
            for (int i = startPageIndex; i <= endPageIndex; i++) {
                if (Thread.currentThread().isInterrupted()) {
                    throw new JRException("Current thread interrupted.");
                }

                page = (JRPrintPage) pages.get(i);

                document.newPage();

                pdfContentByte = pdfWriter.getDirectContent();

                pdfContentByte.setLineCap(2);

                chunk = new Chunk(" ");
                chunk.setLocalDestination("JR_PAGE_ANCHOR_" + (i + 1));

                colText = new ColumnText(pdfContentByte);
                colText.setSimpleColumn(new Phrase(chunk), 0, jasperPrint.getPageHeight(), 1, 1, 0,
                        Element.ALIGN_LEFT);

                colText.go();

                /*   */
                exportPage(page);
            }
        } else {
            document.newPage();
            pdfContentByte = pdfWriter.getDirectContent();
            pdfContentByte.setLiteral("\n");
        }
    } catch (DocumentException e) {
        throw new JRException("PDF Document error : " + jasperPrint.getName(), e);
    } catch (IOException e) {
        throw new JRException("Error generating PDF report : " + jasperPrint.getName(), e);
    } finally {
        document.close();
        imageTesterDocument.close();
    }

    //return os.toByteArray();
}

From source file:com.dlya.facturews.DlyaPdfExporter2.java

License:Open Source License

/**
 *
 *//*from www  .  j  a  va 2 s .  com*/
protected void exportReportToStream(OutputStream os) throws JRException {
    //ByteArrayOutputStream baos = new ByteArrayOutputStream();

    document = new Document(new Rectangle(jasperPrint.getPageWidth(), jasperPrint.getPageHeight()));

    imageTesterDocument = new Document(new Rectangle(10, //jasperPrint.getPageWidth(),
            10 //jasperPrint.getPageHeight()
    ));

    boolean closeDocuments = true;
    try {
        pdfWriter = PdfWriter.getInstance(document, os);
        pdfWriter.setCloseStream(false);

        if (pdfVersion != null) {
            pdfWriter.setPdfVersion(pdfVersion.charValue());
        }
        if (isCompressed) {
            pdfWriter.setFullCompression();
        }
        if (isEncrypted) {
            pdfWriter.setEncryption(is128BitKey, userPassword, ownerPassword, permissions);
        }

        if (printScaling != null) {
            if (JRPdfExporterParameter.PRINT_SCALING_DEFAULT.equals(printScaling)) {
                //pdfWriter.addViewerPreference(PdfName.PRINTSCALING, PdfName.APPDEFAULT);
            } else if (JRPdfExporterParameter.PRINT_SCALING_NONE.equals(printScaling)) {
                //pdfWriter.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
            }
        }

        // Add meta-data parameters to generated PDF document
        // mtclough@users.sourceforge.net 2005-12-05
        String title = (String) parameters.get(JRPdfExporterParameter.METADATA_TITLE);
        if (title != null) {
            document.addTitle(title);
        }
        String author = (String) parameters.get(JRPdfExporterParameter.METADATA_AUTHOR);
        if (author != null) {
            document.addAuthor(author);
        }
        String subject = (String) parameters.get(JRPdfExporterParameter.METADATA_SUBJECT);
        if (subject != null) {
            document.addSubject(subject);
        }
        String keywords = (String) parameters.get(JRPdfExporterParameter.METADATA_KEYWORDS);
        if (keywords != null) {
            document.addKeywords(keywords);
        }
        String creator = (String) parameters.get(JRPdfExporterParameter.METADATA_CREATOR);
        if (creator != null) {
            document.addCreator(creator);
        } else {
            document.addCreator("JasperReports (" + jasperPrint.getName() + ")");
        }

        // BEGIN: PDF/A support
        String pdfaConformance = getStringParameter(JRPdfExporterParameter.PDFA_CONFORMANCE,
                JRPdfExporterParameter.PROPERTY_PDFA_CONFORMANCE);
        boolean gotPdfa = false;
        if (pdfaConformance != null
                && !JRPdfExporterParameter.PDFA_CONFORMANCE_NONE.equalsIgnoreCase(pdfaConformance)) {
            if (JRPdfExporterParameter.PDFA_CONFORMANCE_1A.equalsIgnoreCase(pdfaConformance)) {
                //pdfWriter.setPDFXConformance(PdfWriter.PDFA1A);
                gotPdfa = true;
            } else if (JRPdfExporterParameter.PDFA_CONFORMANCE_1B.equalsIgnoreCase(pdfaConformance)) {
                //pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);
                gotPdfa = true;
            }
        }

        if (gotPdfa) {

            //pdfWriter.createXmpMetadata();
        } else {
            //pdfWriter.setRgbTransparencyBlending(true);
        }
        // END: PDF/A support

        document.open();

        // BEGIN: PDF/A support
        if (gotPdfa) {
            String iccProfilePath = getStringParameter(JRPdfExporterParameter.PDFA_ICC_PROFILE_PATH,
                    JRPdfExporterParameter.PROPERTY_PDFA_ICC_PROFILE_PATH);
            if (iccProfilePath != null) {
                PdfDictionary pdfDictionary = new PdfDictionary(PdfName.OUTPUTINTENT);
                pdfDictionary.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1"));
                pdfDictionary.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
                //pdfDictionary.put(PdfName.S, PdfName.GTS_PDFA1);

                InputStream iccIs = RepositoryUtil.getInstance(jasperReportsContext)
                        .getInputStreamFromLocation(iccProfilePath);
                //PdfICCBased pdfICCBased = new PdfICCBased(ICC_Profile.getInstance(iccIs));
                //pdfICCBased.remove(PdfName.ALTERNATE);
                //pdfDictionary.put(PdfName.DESTOUTPUTPROFILE, pdfWriter.addToBody(pdfICCBased).getIndirectReference());

                pdfWriter.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(pdfDictionary));
            } else {
                throw new JRPdfaIccProfileNotFoundException();
            }
        }
        // END: PDF/A support

        if (pdfJavaScript != null) {
            pdfWriter.addJavaScript(pdfJavaScript);
        }

        pdfContentByte = pdfWriter.getDirectContent();

        //tagHelper.init(pdfContentByte);

        initBookmarks();

        PdfWriter imageTesterPdfWriter = PdfWriter.getInstance(imageTesterDocument, new NullOutputStream() // discard the output
        );
        imageTesterDocument.open();
        imageTesterDocument.newPage();
        imageTesterPdfContentByte = imageTesterPdfWriter.getDirectContent();
        imageTesterPdfContentByte.setLiteral("\n");

        for (reportIndex = 0; reportIndex < jasperPrintList.size(); reportIndex++) {
            setJasperPrint(jasperPrintList.get(reportIndex));
            loadedImagesMap = new HashMap<Renderable, com.lowagie.text.Image>();

            setPageSize(null);

            BorderOffset.setLegacy(JRPropertiesUtil.getInstance(jasperReportsContext)
                    .getBooleanProperty(jasperPrint, BorderOffset.PROPERTY_LEGACY_BORDER_OFFSET, false));

            boolean sizePageToContent = JRPropertiesUtil.getInstance(jasperReportsContext).getBooleanProperty(
                    jasperPrint, JRPdfExporterParameter.PROPERTY_SIZE_PAGE_TO_CONTENT, false);

            List<JRPrintPage> pages = jasperPrint.getPages();
            if (pages != null && pages.size() > 0) {
                if (isModeBatch) {
                    document.newPage();

                    if (isCreatingBatchModeBookmarks) {
                        //add a new level to our outline for this report
                        addBookmark(0, jasperPrint.getName(), 0, 0);
                    }

                    startPageIndex = 0;
                    endPageIndex = pages.size() - 1;
                }

                for (int pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) {
                    if (Thread.interrupted()) {
                        throw new JRException("Current thread interrupted.");
                    }

                    JRPrintPage page = pages.get(pageIndex);

                    if (sizePageToContent) {
                        setPageSize(page);
                    }

                    document.newPage();

                    pdfContentByte = pdfWriter.getDirectContent();

                    pdfContentByte.setLineCap(2);//PdfContentByte.LINE_CAP_PROJECTING_SQUARE since iText 1.02b

                    writePageAnchor(pageIndex);

                    /*   */
                    exportPage(page);
                }
            } else {
                document.newPage();
                pdfContentByte = pdfWriter.getDirectContent();
                pdfContentByte.setLiteral("\n");
            }
        }

        closeDocuments = false;
        document.close();
        imageTesterDocument.close();
    } catch (DocumentException e) {
        throw new JRException("PDF Document error : " + jasperPrint.getName(), e);
    } catch (IOException e) {
        throw new JRException("Error generating PDF report : " + jasperPrint.getName(), e);
    } finally {
        if (closeDocuments) //only on exception
        {
            try {
                document.close();
            } catch (Exception e) {
                // ignore, let the original exception propagate
            }

            try {
                imageTesterDocument.close();
            } catch (Exception e) {
                // ignore, let the original exception propagate
            }
        }
    }

    //return os.toByteArray();
}

From source file:com.dlya.facturews.DlyaPdfExporter2.java

License:Open Source License

/**
 *
 *///www . j  a va 2 s .c  o m
protected void setPageSize(JRPrintPage page) throws JRException, DocumentException, IOException {
    int pageWidth = jasperPrint.getPageWidth();
    int pageHeight = jasperPrint.getPageHeight();

    if (page != null) {
        Collection<JRPrintElement> elements = page.getElements();
        for (JRPrintElement element : elements) {
            int elementRight = element.getX() + element.getWidth();
            int elementBottom = element.getY() + element.getHeight();
            pageWidth = pageWidth < elementRight ? elementRight : pageWidth;
            pageHeight = pageHeight < elementBottom ? elementBottom : pageHeight;
        }

        pageWidth += jasperPrint.getRightMargin();
        pageHeight += jasperPrint.getBottomMargin();
    }

    Rectangle pageSize;
    switch (jasperPrint.getOrientationValue()) {
    case LANDSCAPE:
        // using rotate to indicate landscape page
        pageSize = new Rectangle(pageHeight, pageWidth).rotate();
        break;
    default:
        pageSize = new Rectangle(pageWidth, pageHeight);
        break;
    }
    document.setPageSize(pageSize);
}

From source file:com.eteks.sweethome3d.swing.HomePDFPrinter.java

License:Open Source License

/**
 * Writes to <code>outputStream</code> the print of a home in PDF format.
 *///from   ww  w .  j ava2s . c o  m
public void write(OutputStream outputStream) throws IOException {
    PageFormat pageFormat = HomePrintableComponent.getPageFormat(this.home.getPrint());
    Document pdfDocument = new Document(
            new Rectangle((float) pageFormat.getWidth(), (float) pageFormat.getHeight()));
    try {
        // Get a PDF writer that will write to the given PDF output stream
        PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, outputStream);
        pdfDocument.open();

        // Set PDF document description
        pdfDocument.addAuthor(System.getProperty("user.name", ""));
        String pdfDocumentCreator = this.preferences.getLocalizedString(HomePDFPrinter.class,
                "pdfDocument.creator");
        pdfDocument.addCreator(pdfDocumentCreator);
        pdfDocument.addCreationDate();
        String homeName = this.home.getName();
        if (homeName != null) {
            pdfDocument.addTitle(this.controller.getContentManager().getPresentationName(homeName,
                    ContentManager.ContentType.PDF));
        }

        PdfContentByte pdfContent = pdfWriter.getDirectContent();
        HomePrintableComponent printableComponent = new HomePrintableComponent(this.home, this.controller,
                this.defaultFont);
        // Print each page
        for (int page = 0, pageCount = printableComponent.getPageCount(); page < pageCount; page++) {
            // Check current thread isn't interrupted
            if (Thread.interrupted()) {
                throw new InterruptedIOException();
            }
            PdfTemplate pdfTemplate = pdfContent.createTemplate((float) pageFormat.getWidth(),
                    (float) pageFormat.getHeight());
            Graphics g = pdfTemplate.createGraphicsShapes((float) pageFormat.getWidth(),
                    (float) pageFormat.getHeight());

            printableComponent.print(g, pageFormat, page);

            pdfContent.addTemplate(pdfTemplate, 0, 0);
            g.dispose();

            if (page != pageCount - 1) {
                pdfDocument.newPage();
            }
        }
        pdfDocument.close();
    } catch (DocumentException ex) {
        IOException exception = new IOException("Couldn't print to PDF");
        exception.initCause(ex);
        throw exception;
    } catch (InterruptedPrinterException ex) {
        throw new InterruptedIOException("Print to PDF interrupted");
    } catch (PrinterException ex) {
        IOException exception = new IOException("Couldn't print to PDF");
        exception.initCause(ex);
        throw exception;
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.edit.inctxrv.pdf.PreviewPDFHelper.java

License:Apache License

public static File setCopyOnlyPermission(File p_file) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(p_file.getAbsolutePath());
    String outPutFile = FileUtils.getPrefix(p_file.getAbsolutePath()) + "_hidebars.pdf";
    int n = reader.getNumberOfPages();
    Rectangle psize = reader.getPageSize(1);
    float width = psize.height();
    float height = psize.width();
    Document document = new Document(new Rectangle(width, height));
    PdfCopy writer = new PdfCopy(document, new FileOutputStream(outPutFile));
    writer.setEncryption(PdfWriter.STRENGTH40BITS, null, null, PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
    try {/*w w w  .j  a va 2  s.c om*/
        document.open();
        int i = 0;
        while (i < n) {
            document.newPage();
            i++;
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            writer.addPage(page1);
        }
        document.close();
    } catch (IllegalArgumentException e) {
        if (!e.getMessage().equals("PdfReader not opened with owner password")) {
            throw new EnvoyServletException(e);
        } else {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return new File(outPutFile);
}

From source file:com.globalsight.everest.webapp.pagehandler.edit.online.PreviewPDFPageHandler.java

License:Apache License

public static File setCopyOnlyPermission(File p_file) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(p_file.getAbsolutePath());
    String outPutFile = FileUtils.getPrefix(p_file.getAbsolutePath()) + "_hidebars.pdf";
    int n = reader.getNumberOfPages();
    Rectangle psize = reader.getPageSize(1);
    float width = psize.height();
    float height = psize.width();
    Document document = new Document(new Rectangle(width, height));
    PdfCopy writer = new PdfCopy(document, new FileOutputStream(outPutFile));
    writer.setEncryption(PdfWriter.STRENGTH40BITS, null, null, PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
    try {/*from ww  w .  j  a  v  a2s.c om*/
        document.open();
        int i = 0;
        while (i < n) {
            document.newPage();
            i++;
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            writer.addPage(page1);
        }
        document.close();
    } catch (IllegalArgumentException e) {
        if (!e.getMessage().equals("PdfReader not opened with owner password")) {
            throw new EnvoyServletException(e);
        } else {
            CATEGORY.error(e.getMessage(), e);
        }
    }

    return new File(outPutFile);
}