Example usage for com.lowagie.text Document Document

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

Introduction

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

Prototype


public Document(Rectangle pageSize) 

Source Link

Document

Constructs a new Document -object.

Usage

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 w w  w  .ja  v a2s . 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 {//from w  w  w  .ja  va2 s .c om
        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  ww. j  av a 2  s  .  c om*/
    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

/**
 *
 *///from  w w w.  jav a 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()
    ));

    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   w  ww . j  ava2 s. c o  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()
    ));

    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.efficio.fieldbook.service.LabelPrintingServiceImpl.java

License:Open Source License

/**
 * Gets the cell height./*  w  w  w  . j a  v a 2  s .com*/
 *
 * @param numberOfRowsPerPage the number of rows per page
 * @param pageSizeId the page size id
 * @return the cell height
 */
/*
private float getCellHeight(int numberOfRowsPerPage, int pageSizeId){
if(pageSizeId == AppConstants.SIZE_OF_PAPER_A4){
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 97f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;
    }
}else{
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 98.1f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;//ok
    }
}
           
return 0f;
}
*/
/* (non-Javadoc)
 * @see com.efficio.fieldbook.service.api.LabelPrintingService#generateLabels(com.efficio.fieldbook.web.fieldmap.bean.UserFieldmap)
 */
@Override
public String generatePDFLabels(List<StudyTrialInstanceInfo> trialInstances,
        UserLabelPrinting userLabelPrinting, ByteArrayOutputStream baos) throws MiddlewareQueryException {

    // setUserLabelPrinting(form.getUserLabelPrinting());
    int pageSizeId = Integer.parseInt(userLabelPrinting.getSizeOfLabelSheet());
    int numberOfLabelPerRow = Integer.parseInt(userLabelPrinting.getNumberOfLabelPerRow());
    int numberofRowsPerPageOfLabel = Integer.parseInt(userLabelPrinting.getNumberOfRowsPerPageOfLabel());
    int totalPerPage = numberOfLabelPerRow * numberofRowsPerPageOfLabel;
    String leftSelectedFields = userLabelPrinting.getLeftSelectedLabelFields();
    String rightSelectedFields = userLabelPrinting.getRightSelectedLabelFields();
    String barcodeNeeded = userLabelPrinting.getBarcodeNeeded();

    String firstBarcodeField = userLabelPrinting.getFirstBarcodeField();
    String secondBarcodeField = userLabelPrinting.getSecondBarcodeField();
    String thirdBarcodeField = userLabelPrinting.getThirdBarcodeField();

    String currentDate = DateUtil.getCurrentDate();
    // String fileName = currentDate + ".pdf";

    String fileName = userLabelPrinting.getFilenameDLLocation();

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(fileName);

        try {

            // Image image1 = Image.getInstance(imageLocation);

            // PageSize.A4
            LabelPaper paper = LabelPaperFactory.generateLabelPaper(numberOfLabelPerRow,
                    numberofRowsPerPageOfLabel, pageSizeId);

            Rectangle pageSize = PageSize.LETTER;

            if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4.getInt())
                pageSize = PageSize.A4;

            Document document = new Document(pageSize);
            /*
             * 2, 2, 33.3f, 5
             * 15, 0, 42, 5
             * 10, 0, 17, 5
             * 10, 0, 17, 5
             * 5, 0, 0, 5
             * 15, 0, 37, 5
             * 10, 0, 17, 5
            if (pageSizeId == AppConstants.SIZE_OF_PAPER_LETTER) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(10, 0, 17, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(5, 0, 0, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(2, 2, 33.3f, 5);
            } else if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(15, 0, 42, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(15, 0, 37, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(6, 2, 17.5f, 5);
            }
            */
            //float marginLeft, float marginRight, float marginTop, float marginBottom
            document.setMargins(paper.getMarginLeft(), paper.getMarginRight(), paper.getMarginTop(),
                    paper.getMarginBottom());

            // PdfWriter writer = PdfWriter.getInstance(document, baos);
            PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
            // step 3
            document.open();
            // step 4

            PdfContentByte canvas = writer.getDirectContent();

            int i = 0;
            int fixTableRowSize = numberOfLabelPerRow;
            PdfPTable table = new PdfPTable(fixTableRowSize);

            // table.writeSelectedRows(0, -1, 10, 12, canvas);
            float columnWidthSize = 265f;// 180f;
            float[] widthColumns = new float[fixTableRowSize];

            for (int counter = 0; counter < widthColumns.length; counter++) {
                widthColumns[counter] = columnWidthSize;
            }

            table.setWidths(widthColumns);
            table.setWidthPercentage(100);
            int width = 600;
            int height = 75;

            List<File> filesToBeDeleted = new ArrayList<File>();
            //float cellHeight = getCellHeight(numberofRowsPerPageOfLabel, pageSizeId);
            float cellHeight = paper.getCellHeight();

            for (StudyTrialInstanceInfo trialInstance : trialInstances) {
                FieldMapTrialInstanceInfo fieldMapTrialInstanceInfo = trialInstance.getTrialInstance();

                Map<String, String> moreFieldInfo = new HashMap<String, String>();
                moreFieldInfo.put("locationName", fieldMapTrialInstanceInfo.getLocationName());
                moreFieldInfo.put("blockName", fieldMapTrialInstanceInfo.getBlockName());
                moreFieldInfo.put("selectedName", trialInstance.getFieldbookName());
                moreFieldInfo.put("trialInstanceNumber", fieldMapTrialInstanceInfo.getTrialInstanceNo());

                for (FieldMapLabel fieldMapLabel : fieldMapTrialInstanceInfo.getFieldMapLabels()) {

                    i++;
                    String barcodeLabel = generateBarcodeField(moreFieldInfo, fieldMapLabel, firstBarcodeField,
                            secondBarcodeField, thirdBarcodeField, barcodeNeeded);
                    if ("0".equalsIgnoreCase(barcodeNeeded)) {
                        barcodeLabel = " ";
                    }

                    BitMatrix bitMatrix = new Code128Writer().encode(barcodeLabel, BarcodeFormat.CODE_128,
                            width, height, null);
                    String imageLocation = System.getProperty("user.home") + "/" + Math.random() + ".png";
                    File imageFile = new File(imageLocation);
                    FileOutputStream fout = new FileOutputStream(imageFile);
                    MatrixToImageWriter.writeToStream(bitMatrix, "png", fout);
                    filesToBeDeleted.add(imageFile);

                    Image mainImage = Image.getInstance(imageLocation);

                    PdfPCell cell = new PdfPCell();
                    cell.setFixedHeight(cellHeight);
                    cell.setNoWrap(false);
                    cell.setPadding(5f);
                    cell.setPaddingBottom(1f);

                    PdfPTable innerImageTableInfo = new PdfPTable(1);
                    innerImageTableInfo.setWidths(new float[] { 1 });
                    innerImageTableInfo.setWidthPercentage(82);
                    PdfPCell cellImage = new PdfPCell();
                    if ("1".equalsIgnoreCase(barcodeNeeded)) {
                        cellImage.addElement(mainImage);
                    } else {
                        cellImage.addElement(new Paragraph(" "));
                    }
                    cellImage.setBorder(Rectangle.NO_BORDER);
                    cellImage.setBackgroundColor(Color.white);
                    cellImage.setPadding(1.5f);

                    innerImageTableInfo.addCell(cellImage);

                    //float fontSize = 6.8f;
                    float fontSize = paper.getFontSize();
                    //if (numberofRowsPerPageOfLabel == 10)
                    //    fontSize = 4.8f;

                    Font fontNormal = FontFactory.getFont("Arial", fontSize, Font.NORMAL);

                    // cell.addElement(mainImage);
                    cell.addElement(innerImageTableInfo);

                    cell.addElement(new Paragraph());
                    for (int row = 0; row < 5; row++) {
                        if (row == 0) {
                            PdfPTable innerDataTableInfo = new PdfPTable(1);
                            innerDataTableInfo.setWidths(new float[] { 1 });
                            innerDataTableInfo.setWidthPercentage(85);

                            Font fontNormalData = FontFactory.getFont("Arial", 5.0f, Font.NORMAL);
                            PdfPCell cellInnerData = new PdfPCell(new Phrase(barcodeLabel, fontNormalData));

                            cellInnerData.setBorder(Rectangle.NO_BORDER);
                            cellInnerData.setBackgroundColor(Color.white);
                            cellInnerData.setPaddingBottom(0.2f);
                            cellInnerData.setPaddingTop(0.2f);
                            cellInnerData.setHorizontalAlignment(Element.ALIGN_MIDDLE);

                            innerDataTableInfo.addCell(cellInnerData);
                            innerDataTableInfo.setHorizontalAlignment(Element.ALIGN_MIDDLE);
                            cell.addElement(innerDataTableInfo);
                        }
                        PdfPTable innerTableInfo = new PdfPTable(2);
                        innerTableInfo.setWidths(new float[] { 1, 1 });
                        innerTableInfo.setWidthPercentage(85);

                        String leftText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel, leftSelectedFields,
                                row);
                        PdfPCell cellInnerLeft = new PdfPCell(new Paragraph(leftText, fontNormal));

                        cellInnerLeft.setBorder(Rectangle.NO_BORDER);
                        cellInnerLeft.setBackgroundColor(Color.white);
                        cellInnerLeft.setPaddingBottom(0.5f);
                        cellInnerLeft.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerLeft);

                        String rightText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel,
                                rightSelectedFields, row);
                        PdfPCell cellInnerRight = new PdfPCell(new Paragraph(rightText, fontNormal));

                        cellInnerRight.setBorder(Rectangle.NO_BORDER);
                        cellInnerRight.setBackgroundColor(Color.white);
                        cellInnerRight.setPaddingBottom(0.5f);
                        cellInnerRight.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerRight);

                        cell.addElement(innerTableInfo);
                    }

                    cell.setBorder(Rectangle.NO_BORDER);
                    cell.setBackgroundColor(Color.white);

                    //cell.setBorderColor(Color.BLUE);

                    table.addCell(cell);

                    if (i % numberOfLabelPerRow == 0) {
                        // we go the next line

                        int needed = fixTableRowSize - numberOfLabelPerRow;

                        for (int neededCount = 0; neededCount < needed; neededCount++) {
                            PdfPCell cellNeeded = new PdfPCell();

                            cellNeeded.setBorder(Rectangle.NO_BORDER);
                            cellNeeded.setBackgroundColor(Color.white);

                            table.addCell(cellNeeded);
                        }

                        table.completeRow();
                        if (numberofRowsPerPageOfLabel == 10) {

                            //table.setSpacingAfter(9f);
                            table.setSpacingAfter(paper.getSpacingAfter());
                        }

                        document.add(table);

                        table = new PdfPTable(fixTableRowSize);
                        table.setWidths(widthColumns);
                        table.setWidthPercentage(100);

                    }
                    if (i % totalPerPage == 0) {
                        // we go the next page
                        document.newPage();
                    }
                    fout.flush();
                    fout.close();

                }
            }
            // we need to add the last row
            if (i % numberOfLabelPerRow != 0) {
                // we go the next line

                int needed = fixTableRowSize - numberOfLabelPerRow;
                int remaining = numberOfLabelPerRow - (i % numberOfLabelPerRow);
                for (int neededCount = 0; neededCount < remaining; neededCount++) {
                    PdfPCell cellNeeded = new PdfPCell();

                    cellNeeded.setBorder(Rectangle.NO_BORDER);
                    cellNeeded.setBackgroundColor(Color.white);

                    table.addCell(cellNeeded);
                }

                table.completeRow();
                if (numberofRowsPerPageOfLabel == 10) {

                    table.setSpacingAfter(paper.getSpacingAfter());
                }

                document.add(table);

                table = new PdfPTable(fixTableRowSize);
                table.setWidths(widthColumns);
                table.setWidthPercentage(100);

            }

            document.close();
            for (File file : filesToBeDeleted) {
                file.delete();
            }
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

    } catch (WriterException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return fileName;
}

From source file:com.efficio.fieldbook.web.demo.controller.BarCodeController.java

License:Open Source License

/**
 * Upload file.//w  w  w .j av a  2 s. c om
 *
 * @param uploadForm the upload form
 * @param result the result
 * @param model the model
 * @return the string
 */
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public String uploadFile(@ModelAttribute("barCodeForm") BarCodeForm barCodeForm, BindingResult result,
        Model model, HttpServletResponse response) {
    int width = 60;
    int height = 48;
    String delimeter = "|";
    StringBuilder barCodeString = new StringBuilder();

    barCodeString.append(barCodeForm.getEntryNo()).append(delimeter).append(barCodeForm.getGid())
            .append(delimeter).append(barCodeForm.getDesignation()).append(delimeter)
            .append(barCodeForm.getName()).append(delimeter).append(barCodeForm.getRep()).append(delimeter)
            .append(barCodeForm.getColumn()).append(delimeter).append(barCodeForm.getRange());

    BitMatrix bitMatrix;
    try {
        String barCodeLabel = "3|SM114-1A-1-1-1B";
        //barCodeLabel = barCodeString.toString();
        bitMatrix = new Code128Writer().encode(barCodeLabel, BarcodeFormat.CODE_128, width, height, null);
        String imageLocation = Math.random() + ".png"; //"src/test/resources/barcode/zxing_barcode.png";
        MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(new File(imageLocation)));

        String currentDate = DateUtil.getCurrentDate();
        String fileName = currentDate + ".doc";

        response.setHeader("Content-disposition", "attachment; filename=" + fileName);

        File xls = new File(fileName); // the selected name + current date
        FileInputStream in;

        try {

            Image image1 = Image.getInstance(imageLocation);
            //image1.scalePercent(50);
            //image1.setAbsolutePosition(10f, 10f);
            //document.add(image1);

            //PageSize.A4
            Document document = new Document(PageSize.LETTER);
            // step 2
            PdfWriter.getInstance(document, new FileOutputStream(fileName));
            // step 3
            document.open();
            // step 4
            // we'll use 4 images in this example
            /*
            Image[] img = {
                 Image.getInstance(String.format(RESOURCE, "0120903")),
                 Image.getInstance(String.format(RESOURCE, "0290334")),
                 Image.getInstance(String.format(RESOURCE, "0376994")),
                 Image.getInstance(String.format(RESOURCE, "0348150"))
            };*/

            PdfPTable table = new PdfPTable(4);
            table.setWidthPercentage(100);
            // first movie
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            Phrase phrase = new Phrase();
            phrase.add("Entry # " + barCodeForm.getEntryNo());
            phrase.add("\n");
            phrase.add("Designation " + barCodeForm.getDesignation());
            phrase.add("\n");
            phrase.add("Rep " + barCodeForm.getRep());
            phrase.add("\n");
            phrase.add("GID " + barCodeForm.getGid());
            phrase.add("\n");
            phrase.add("Trial/Nursery Name " + barCodeForm.getName());
            phrase.add("\n");
            phrase.add("Col " + barCodeForm.getColumn());
            phrase.add("\n");
            phrase.add("Range " + barCodeForm.getRange());
            table.addCell(phrase);
            // we add the image with addCell()
            table.addCell(image1);

            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell("X-Men: The Last Stand");
            // we add the image with addCell()
            table.addCell(image1);

            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell("X-Men: The Last Stand");
            // we add the image with addCell()
            table.addCell(image1);

            // we complete the table (otherwise the last row won't be rendered)
            table.completeRow();
            document.add(table);

            document.close();

            in = new FileInputStream(xls);
            OutputStream out = response.getOutputStream();

            byte[] buffer = new byte[BUFFER_SIZE]; // use bigger if you want
            int length = 0;

            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

        return "";

    } catch (WriterException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    return show(barCodeForm, model);
}

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.
 *///w w w . ja  v  a2 s  .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 {// ww  w .j  av  a  2s . co m
        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 www.  j ava  2 s . co m
        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);
}