Example usage for com.lowagie.text.pdf PdfWriter getInstance

List of usage examples for com.lowagie.text.pdf PdfWriter getInstance

Introduction

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

Prototype


public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

From source file:ca.sqlpower.architect.swingui.action.ExportPlaypenToPDFAction.java

License:Open Source License

@Override
public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) {
    logger.debug("Creating PDF of playpen: " + getPlaypen());

    //This is the current play pen snapshot at the time of starting the worker
    //thread. This way the play pen doesn't change while it is printing.
    PlayPen pp = playPen;//w w  w.  j a  va2s.c  om

    /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) 
     * so nothing is drawn right on the edge of the document. So
     * we multiply by 2 so we can accomodate the translate and ensure
     * nothing gets drawn outside of the document size.
     */
    final int width = pp.getBounds().width + 2 * OUTSIDE_PADDING;
    final int height = pp.getBounds().height + 2 * OUTSIDE_PADDING;
    final Rectangle ppSize = new Rectangle(width, height);

    OutputStream out = null;
    Document d = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY)));
        d = new Document(ppSize);

        d.addTitle(Messages.getString("ExportPlaypenToPDFAction.PdfTitle")); //$NON-NLS-1$
        d.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$
        d.addCreator(Messages.getString("ExportPlaypenToPDFAction.powerArchitectVersion") //$NON-NLS-1$
                + ArchitectVersion.APP_FULL_VERSION);

        PdfWriter writer = PdfWriter.getInstance(d, out);
        d.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphicsShapes(width, height);
        // ensure a margin
        g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING);
        PlayPenContentPane contentPane = pp.getContentPane();
        for (int i = 0; i < contentPane.getChildren().size(); i++) {
            PlayPenComponent ppc = contentPane.getChildren().get(i);
            if (logger.isDebugEnabled()) {
                logger.debug("Painting component " + ppc);
            }
            g.translate(ppc.getLocation().x, ppc.getLocation().y);
            Font gFont = g.getFont();
            ppc.paint(g);
            g.setFont(gFont);
            g.translate(-ppc.getLocation().x, -ppc.getLocation().y);
            monitor.setProgress(i);
        }
        pp.paintComponent(g);
        g.dispose();
    } catch (Exception ex) {
        ASUtils.showExceptionDialog(getSession(),
                Messages.getString("ExportPlaypenToPDFAction.couldNotExportPlaypen"), //$NON-NLS-1$
                ex);
    } finally {
        if (d != null) {
            try {
                d.close();
            } catch (Exception ex) {
                ASUtils.showExceptionDialog(getSession(),
                        Messages.getString("ExportPlaypenToPDFAction.couldNotCloseDocument"), //$NON-NLS-1$
                        ex);
            }
        }
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException ex) {
                ASUtils.showExceptionDialog(getSession(),
                        Messages.getString("ExportPlaypenToPDFAction.couldNotClosePdfFile"), //$NON-NLS-1$
                        ex);
            }
        }
    }
}

From source file:ca.sqlpower.matchmaker.swingui.action.ExportMungePenToPDFAction.java

License:Open Source License

@Override
public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) {
    if (!(session.getOldPane() instanceof MungeProcessEditor)) {
        JOptionPane.showMessageDialog(session.getFrame(),
                "We only allow PDF exports of the playpen at current.", "Cannot Export Playpen",
                JOptionPane.WARNING_MESSAGE);
        return;/*  w ww.j  a v a  2  s.  co  m*/
    }

    MungePen mungePen = ((MungeProcessEditor) session.getOldPane()).getMungePen();

    /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) 
     * so nothing is drawn right on the edge of the document. So
     * we multiply by 2 so we can accomodate the translate and ensure
     * nothing gets drawn outside of the document size.
     */
    final int width = mungePen.getBounds().width + 2 * OUTSIDE_PADDING;
    final int height = mungePen.getBounds().height + 2 * OUTSIDE_PADDING;
    final Rectangle ppSize = new Rectangle(width, height);

    OutputStream out = null;
    Document d = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY)));
        d = new Document(ppSize);

        d.addTitle("DQguru Transform PDF Export");
        d.addAuthor(System.getProperty("user.name"));
        d.addCreator("DQguru version " + MatchMakerVersion.APP_VERSION);

        PdfWriter writer = PdfWriter.getInstance(d, out);
        d.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphicsShapes(width, height);
        // ensure a margin
        g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING);

        mungePen.paintComponent(g);

        int j = 0;
        //paint each component individually to show progress
        for (int i = mungePen.getComponentCount() - 1; i >= 0; i--) {
            JComponent mpc = (JComponent) mungePen.getComponent(i);

            //set text and foreground as paintComponent
            //does not normally do this
            g.setColor(mpc.getForeground());
            g.setFont(mpc.getFont());

            logger.debug("Printing " + mpc.getName() + " to PDF");
            paintComponentAndChildren(mpc, g);

            monitor.setProgress(j);
            j++;
        }
        g.dispose();
    } catch (Exception ex) {
        SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not export the playpen", ex);
    } finally {
        if (d != null) {
            try {
                d.close();
            } catch (Exception ex) {
                SPSUtils.showExceptionDialogNoReport(session.getFrame(),
                        "Could not close document for exporting playpen", ex);
            }
        }
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException ex) {
                SPSUtils.showExceptionDialogNoReport(session.getFrame(),
                        "Could not close pdf file for exporting playpen", ex);
            }
        }
    }
}

From source file:candelaria.presentacion.beans.DetalleFacturaControlador.java

public void imprimirFac() {
    //DateFormat dfDateFull = DateFormat.getDateInstance(DateFormat.FULL);
    try {// ww w .jav a 2 s  .  c o m

        //Generamos el archivo PDF
        String directorioArchivos;
        ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        directorioArchivos = ctx.getRealPath("/") + "reports";
        String name = directorioArchivos + "/document-factura.pdf";
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(name));
        //PdfWriter writer = PdfWriter.getInstance(document,
        //new FileOutputStream("C:"));

        Paragraph paragraph = new Paragraph();
        Paragraph paragraph1 = new Paragraph();
        PdfPTable table = new PdfPTable(4);
        PdfPTable table1 = new PdfPTable(2);
        PdfPTable table2 = new PdfPTable(1);
        PdfPTable table3 = new PdfPTable(2);
        PdfPTable table5 = new PdfPTable(4);
        PdfPTable tablaF = new PdfPTable(1);
        PdfPTable tablaF1 = new PdfPTable(3);
        PdfPTable tablaF2 = new PdfPTable(3);

        paragraph.add("\n\n\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        paragraph.add("YUQUI OLGA");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("Dir. La Candelaria Barrio Nuevo");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("Telf: 3014019");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("Penipe - Ecuador");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("AUTORIZACION SRI __________ - RUC.: 0600750897001");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);
        paragraph.add("\n");
        paragraph.add("FACTURA: " + facturaSel.getId_factura());
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        paragraph.add("\n\n\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        paragraph1.add("\n\n");
        paragraph.setAlignment(Paragraph.ALIGN_CENTER);

        document.open();

        //primera linea   
        PdfPCell cell5 = new PdfPCell(new Paragraph("Fecha: " + fecha_cambiada));
        //PdfPCell cell6 = new PdfPCell(new Paragraph("Factura #: " + facturaSel.getId_factura()));
        PdfPCell cell7 = new PdfPCell(new Paragraph("Cedula: " + facturaSel.getId_cliente().getRuc_cliente()));
        //segunda linea
        PdfPCell cell8 = new PdfPCell(
                new Paragraph("Nombre Cliente: " + facturaSel.getId_cliente().getNombres_cliente()
                        + facturaSel.getId_cliente().getApellidos_cliente()));
        //tercera fila
        PdfPCell cell9 = new PdfPCell(
                new Paragraph("Direccin: " + facturaSel.getId_cliente().getDireccion_cliente()));
        PdfPCell cell10 = new PdfPCell(
                new Paragraph("Tlefono: " + facturaSel.getId_cliente().getTelefono_cliente()));

        PdfPCell cellf1 = new PdfPCell(new Paragraph("SubTotal     " + totalHoja));
        PdfPCell cellf2 = new PdfPCell(new Paragraph("Impuesto Iva " + impuestoFactura));
        PdfPCell cellf21 = new PdfPCell(new Paragraph("___________________"));
        PdfPCell cellf22 = new PdfPCell(new Paragraph("___________________"));
        PdfPCell cellf3 = new PdfPCell(new Paragraph("TOTAL        " + totalFactura));
        PdfPCell cellf31 = new PdfPCell(new Paragraph("FIRMA AUTORIZADA"));
        PdfPCell cellf32 = new PdfPCell(new Paragraph("FIRMA CLIENTE"));
        PdfPCell cell11 = new PdfPCell(new Paragraph("Cantidad"));
        PdfPCell cell12 = new PdfPCell(new Paragraph("Descripcin"));
        PdfPCell cell13 = new PdfPCell(new Paragraph("V. Unitario"));
        PdfPCell cell14 = new PdfPCell(new Paragraph("V. Total"));

        cell5.setHorizontalAlignment(Element.ALIGN_LEFT);
        //cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell7.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cellf1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellf2.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellf3.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cellf21.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellf31.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellf22.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellf32.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell8.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell9.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell10.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cellf21.setBorder(Rectangle.NO_BORDER);
        cellf31.setBorder(Rectangle.NO_BORDER);
        cellf22.setBorder(Rectangle.NO_BORDER);
        cellf32.setBorder(Rectangle.NO_BORDER);

        cell5.setBorder(Rectangle.NO_BORDER);
        //cell6.setBorder(Rectangle.NO_BORDER);
        cell7.setBorder(Rectangle.NO_BORDER);
        cell8.setBorder(Rectangle.NO_BORDER);

        cell9.setBorder(Rectangle.NO_BORDER);
        cell10.setBorder(Rectangle.NO_BORDER);
        //cell7.setBorder(Rectangle.NO_BORDER);
        //cell8.setBorder(Rectangle.NO_BORDER);

        cell11.setBorder(Rectangle.NO_BORDER);
        cell12.setBorder(Rectangle.NO_BORDER);
        cell13.setBorder(Rectangle.NO_BORDER);
        cell14.setBorder(Rectangle.NO_BORDER);

        cellf1.setBorder(Rectangle.NO_BORDER);
        cellf2.setBorder(Rectangle.NO_BORDER);
        cellf3.setBorder(Rectangle.NO_BORDER);

        cell11.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell12.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell13.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell14.setHorizontalAlignment(Element.ALIGN_RIGHT);

        table1.addCell(cell5);
        //table1.addCell(cell6);
        table1.addCell(cell7);
        //aadir segunda fila
        table2.addCell(cell8);
        //aadir tercera fila
        table3.addCell(cell9);
        table3.addCell(cell10);
        //aadir cuarta fila
        table5.addCell(cell11);
        table5.addCell(cell12);
        table5.addCell(cell13);
        table5.addCell(cell14);
        tablaF.addCell(cellf1);

        tablaF1.addCell(cellf21);
        tablaF1.addCell(cellf22);
        tablaF1.addCell(cellf2);
        tablaF2.addCell(cellf31);
        tablaF2.addCell(cellf32);
        tablaF2.addCell(cellf3);

        for (int x = 0; x < lstDetalleFactura.size(); x++) {

            PdfPCell cell1 = new PdfPCell(new Paragraph("" + lstDetalleFactura.get(x).getCantidad()));
            PdfPCell cell2 = new PdfPCell(new Paragraph(
                    "" + lstDetalleFactura.get(x).getId_producto().getId_categoria().getNombre_producto()));
            PdfPCell cell3 = new PdfPCell(new Paragraph(
                    "" + lstDetalleFactura.get(x).getId_producto().getId_categoria().getPrecio_producto()));
            PdfPCell cell4 = new PdfPCell(new Paragraph("" + lstDetalleFactura.get(x).getValor_total()));
            /* Chunk chunk = new Chunk(
             "\n" + lstDetalles.get(x).getCantidadDet() + "       " + lstDetalles.get(x).getIdSer().getNombreSer() + "             " + lstDetalles.get(x).getIdSer().getPrecioSer()
             + "                          " + lstDetalles.get(x).getPrecio());*/

            cell1.setBorder(Rectangle.NO_BORDER);
            cell2.setBorder(Rectangle.NO_BORDER);
            cell3.setBorder(Rectangle.NO_BORDER);
            cell4.setBorder(Rectangle.NO_BORDER);

            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell4.setHorizontalAlignment(Element.ALIGN_RIGHT);

            cell1.setMinimumHeight(10f);
            cell2.setMinimumHeight(5f);

            table.setTotalWidth(100f);
            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);
            table.addCell(cell4);

            //aadir primera fila
            table.setSpacingBefore(30f);
            table.setSpacingAfter(50f);

            //paragraph4.add(chunk);
            //paragraph4.setAlignment(Paragraph.ALIGN_JUSTIFIED_ALL);
        }

        document.add(paragraph);
        document.add(table1);
        document.add(table2);
        document.add(table3);
        document.add(paragraph1);
        document.add(table5);
        document.add(table);
        document.add(tablaF);
        document.add(tablaF1);
        document.add(tablaF2);
        //document.setFooter(event);

        document.close();
        //----------------------------
        //Abrimos el archivo PDF
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline=filename=" + name);
        try {
            response.getOutputStream().write(Util.getBytesFromFile(new File(name)));
            response.getOutputStream().flush();
            response.getOutputStream().close();
            context.responseComplete();

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

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

}

From source file:ch.elexis.omnivore.data.DocHandle.java

License:Open Source License

public static List<DocHandle> assimilate(List<ImageData> images) {
    List<DocHandle> ret = new ArrayList<DocHandle>();
    FileImportDialog fid = new FileImportDialog(Messages.DocHandle_scannedImageDialogCaption);
    if (fid.open() == Dialog.OK) {
        try {/*  w  ww .j a v  a2  s .  co  m*/
            Document pdf = new Document(PageSize.A4);
            pdf.setMargins(0, 0, 0, 0);
            ByteArrayOutputStream baos = new ByteArrayOutputStream(100000);
            PdfWriter.getInstance(pdf, baos);
            pdf.open();
            ImageLoader il = new ImageLoader();
            for (int i = 0; i < images.size(); i++) {
                ImageData[] id = new ImageData[] { images.get(i) };
                il.data = id;
                ByteArrayOutputStream bimg = new ByteArrayOutputStream();
                il.save(bimg, SWT.IMAGE_PNG);
                Image image = Image.getInstance(bimg.toByteArray());
                int width = id[0].width;
                int height = id[0].height;
                // 210mm = 8.27 In = 595 px bei 72dpi
                // 297mm = 11.69 In = 841 px
                if ((width > 595) || (height > 841)) {
                    image.scaleToFit(595, 841);
                }
                pdf.add(image);
            }
            pdf.close();
            DocHandle docHandle = new DocHandle(fid.category, baos.toByteArray(),
                    ElexisEventDispatcher.getSelectedPatient(), fid.originDate, fid.title, "image.pdf", //$NON-NLS-1$
                    fid.keywords);
            ret.add(docHandle);
        } catch (Exception ex) {
            ExHandler.handle(ex);
            SWTHelper.showError(Messages.DocHandle_readError, Messages.DocHandle_readErrorText2);
        }
    }
    return ret;
}

From source file:ch.emad.business.schuetu.print.PrintAgent.java

License:Apache License

public void saveFileToPrint(String name, String htmlContent) {
    OutputStream os = null;//from  w  ww . j a v a2s  . c  o  m
    try {

        if (!this.init) {
            map.put(name, htmlContent);
            return;
        }

        CleanerProperties props = new CleanerProperties();

        // set some properties to non-default values
        props.setTranslateSpecialEntities(true);
        props.setTransResCharsToNCR(true);
        props.setOmitComments(true);

        // do parsing
        LOG.info("HtmlCleaner! Body wegnehmen");
        TagNode tagNode = new HtmlCleaner(props).clean(htmlContent);

        Object[] o = tagNode.evaluateXPath("//body");

        // serialize to xml file
        new PrettyXmlSerializer(props).writeToFile(
                //  --> mit utf-8 wurden sonderzeichen falsch gedruckt pathprinter+"out.xml", "utf-8"
                (TagNode) o[0], pathprinter + "out.xml");

        String outputFile = pathprinter + name + ".pdf";
        os = new FileOutputStream(outputFile);

        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, os);
        doc.open();
        HTMLWorker hw = new HTMLWorker(doc);

        hw.parse(new FileReader(pathprinter + "out.xml"));
        doc.close();

        if (this.applicationEventPublisher != null) {
            ch.emad.model.schuetu.model.integration.File file = new ch.emad.model.schuetu.model.integration.File();
            file.setContent(IOUtils.toByteArray(new FileInputStream(new File(outputFile))));
            file.setName(name + ".pdf");
            OutgoingMessage fileOut = new OutgoingMessage(this);
            fileOut.setPayload(file);
            this.applicationEventPublisher.publishEvent(fileOut);
        }

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
    FileUtils.deleteQuietly(new File(pathprinter + "out.xml"));
}

From source file:ch.gpb.elexis.cst.view.CstResultPart.java

License:Open Source License

private void makeActions(final Control viewer) {

    actionScreenshot = new Action() {
        public void run() {
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }/* ww  w .ja  va2  s . c  o  m*/

            GC gc = null;
            Image image = null;
            try {

                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.png", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }

                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                //if (profile.getAnzeigeTyp().toLowerCase().equals("effektiv")) {
                if (profile.getAnzeigeTyp().toLowerCase().equals(CstProfile.ANZEIGETYP_EFFEKTIV)) {

                    if (profile.getAusgabeRichtung()) {
                        image = new Image(viewer.getDisplay(), 1123, viewer.getBounds().height);

                    } else {
                        image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                    }
                } else {
                    image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                }

                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);

                gc.dispose();

                loader.data = new ImageData[] { image.getImageData() };
                loader.save(selected, SWT.IMAGE_PNG);

            } catch (Exception e) {
                log.error("Error saving png: " + e.toString());
                showMessage("Error while saving PNG", e.getMessage());
            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
            }

        }
    };
    actionScreenshot.setText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setToolTipText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ELEMENT));
    actionScreenshot.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PNG_PATH));

    // TODO: die pdf ausgabe ist eine ziemliche Baustelle - berarbeiten
    actionPdf = new Action() {
        public void run() {

            //////////////////////////
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }

            GC gc = null;
            Image image = null;
            try {
                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.pdf", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }
                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                int printHeigth = 1123;
                int printWidth = 794;
                if (profile.getAusgabeRichtung()) {
                    printHeigth = 794;
                    printWidth = 1123;

                }

                // get the image from the viewport
                image = new Image(viewer.getDisplay(), printWidth, viewer.getBounds().height);
                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);
                gc.dispose();

                // prepare title data
                //Date date = new Date();
                //SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy  HH:mm");

                Patient patient = Patient.load(profile.getKontaktId());
                //String sTitle = "Gemeinschaftspraxis Brunnmatt Dr. Beat Knzi ";
                String sTitle;
                sTitle = profile.getOutputHeader() == null ? "No header configured!"
                        : profile.getOutputHeader();

                if (sTitle == null || sTitle.length() == 0) {
                    sTitle = "No header configured!";
                }
                sTitle = sTitle + " Datum: " + CstService.getReadableDateAndTime();

                // get option (paging to A4/ in one piece)
                int pdfOutputOption = 0;
                boolean onePage = true;

                PdfOptionsDialog dialog = new PdfOptionsDialog(baseComposite.getShell());
                dialog.create();

                if (dialog.open() == Window.OK) {
                    pdfOutputOption = dialog.getPdfOutputOption();
                    if (pdfOutputOption == PdfOptionsDialog.OPTION_ONE_PAGE) {
                        onePage = true;
                    } else {

                        onePage = false;
                    }
                }

                float docHeight = viewer.getBounds().height;
                docHeight = docHeight / 7.5f;

                float fontSize = 12f;

                if (docHeight < 360f) {
                    docHeight = 360f;
                }

                BufferedImage bimage = ImageUtils.convertToAWT(image.getImageData());

                // create an Itextt Image from AWT BufferedImage
                com.lowagie.text.Image itextImage = null;
                java.awt.Image awtImage = null;

                try {
                    awtImage = Toolkit.getDefaultToolkit().createImage(bimage.getSource());
                    itextImage = com.lowagie.text.Image.getInstance(awtImage, null);

                } catch (Exception e) {
                    log.error("Error on image loading: " + e.toString());
                    e.printStackTrace();
                }

                // only for debugging

                //loader.data = new ImageData[] { image.getImageData() };
                //loader.save("C:\\Users\\daniel\\tmp\\debug.png", SWT.IMAGE_PNG);

                Rectangle pagesize = new Rectangle(595f, itextImage.getHeight() * 0.75f);

                // is it a4 quer?
                if (profile.getAusgabeRichtung()) {
                    pagesize = new Rectangle(842f, itextImage.getHeight() * 0.75f);

                }

                //System.out.println("pagesize: " + pagesize.toString());

                Document document;
                if (onePage) {
                    document = new Document(pagesize);

                } else {
                    document = new Document(PageSize.A4);
                    if (profile.getAusgabeRichtung()) {
                        document = new Document(PageSize.A4.rotate());
                    }

                }

                document.addCreationDate();

                try {
                    // creation of the different writers
                    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(selected));

                    // various fonts
                    BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true);
                    BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true);
                    BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", true);

                    com.lowagie.text.Font fontHelv12 = new com.lowagie.text.Font(bf_helv, fontSize);

                    com.lowagie.text.Font fontTimes = new com.lowagie.text.Font(bf_times, fontSize);

                    fontTimes.setSize(fontSize);
                    fontTimes.setStyle(com.lowagie.text.Font.ITALIC);

                    Chunk chunkHeader = new Chunk(sTitle, FontFactory.getFont(FontFactory.HELVETICA, fontSize,
                            com.lowagie.text.Font.NORMAL, new java.awt.Color(255, 0, 0)));

                    com.lowagie.text.Phrase phraseHeader = new com.lowagie.text.Phrase(chunkHeader);

                    // headers and footers must be added before the document
                    // is opened

                    Chunk chunkFooter = new Chunk("Seite: ", FontFactory.getFont(FontFactory.HELVETICA,
                            fontSize, com.lowagie.text.Font.BOLD, new java.awt.Color(0, 0, 0)));

                    Phrase phraseFooter = new Phrase(chunkFooter);
                    phraseFooter.setFont(fontHelv12);

                    HeaderFooter footer = new HeaderFooter(phraseFooter, true);
                    footer.setBorder(Rectangle.NO_BORDER);
                    footer.setAlignment(Element.ALIGN_CENTER);

                    document.setFooter(footer);

                    Phrase headerPhrase = new Phrase(sTitle);
                    headerPhrase.setFont(fontTimes);

                    HeaderFooter header = new HeaderFooter(phraseHeader, false);
                    header.setBorder(Rectangle.BOTTOM);
                    header.setBorderWidth(0.5f);
                    header.setAlignment(Element.ALIGN_LEFT);
                    document.setHeader(header);

                    document.open();

                    //System.out.println("itext image w: " + itextImage.getWidth() + " h:" + itextImage.getHeight());

                    if (onePage) {

                        int scale = 66;
                        itextImage.scalePercent(scale);

                        document.add(itextImage);

                    } else {

                        BufferedImage[] imageChunks = ImageUtils.splitImageByHeigth(bimage, printHeigth);

                        for (int i = 0; i < imageChunks.length; i++) {

                            com.lowagie.text.Image itextImage2 = com.lowagie.text.Image.getInstance(
                                    Toolkit.getDefaultToolkit().createImage(imageChunks[i].getSource()), null);

                            // width becomes typically 523 (595 - 72) for a4Hoch or 770 (842 - 72) for A4Quer
                            float imgWidth = document.getPageSize().getWidth() - document.leftMargin()
                                    - document.rightMargin();
                            float imgHeigth = itextImage.getHeight() * 0.75f;

                            itextImage2.setAbsolutePosition(30, 20);
                            int scale = 66;
                            itextImage2.scalePercent(scale);

                            document.add(itextImage2);
                            document.newPage();

                        }

                    }

                    // we're done!
                    document.close();

                    ///////////////////////////////

                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    showMessage("Error while generating PDF", ex.getMessage());
                }

            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
                /*
                image.dispose();
                gc.dispose();
                */
            }

        }
    };

    actionPdf.setText(Messages.Cst_Text_Save_as_pdf);
    actionPdf.setToolTipText(Messages.Cst_Text_Save_as_pdf);
    /*
     * actionPdf.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages()
     * .getImageDescriptor(ISharedImages.IMG_OBJ_FILE));
     */
    actionPdf.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PDF_PATH));

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createLaborwertTable(Patient patient, String filename, LinkedList<String[]> laborBlatt,
        String footerText) throws IOException, DocumentException {

    // step 1/*from   w w w .  jav  a2 s.  c  om*/
    Document document = new Document(PageSize.A4);

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    writer.setBoxSize("art", rect);

    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    event.setHeaderText(
            patient.getVorname() + " " + patient.getName() + " (" + patient.getGeburtsdatum() + ")");
    event.setFooterText(footerText);
    writer.setPageEvent(event);

    document.setMargins(56, 72, 60, 60);

    // step 3
    document.open();

    if (laborBlatt.size() == 0) {
        Paragraph p = new Paragraph(new Chunk("Keine Laborwerte vorhanden", fontTimesTitle));
        p.setSpacingBefore(20f);
        document.add(p);
    } else {

        document.add(createTable2(laborBlatt));
    }

    // step 5
    document.close();

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createPdf(Patient patient, String filename, LinkedList<String[]> laborBlatt)
        throws IOException, DocumentException {

    BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true);
    fontTimes = new com.lowagie.text.Font(bf_helv, 6);

    // step 1/*from   w w  w. j  av  a 2  s  .  co  m*/
    Document document = new Document(PageSize.A4.rotate());

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3

    document.setHeader(getHeader(
            patient.getVorname() + " " + patient.getName() + "   Geburtsdatum: " + patient.getGeburtsdatum()));

    document.open();

    document.add(new Chunk("")); // << this will do the trick. 

    // step 4
    document.add(createTable2(laborBlatt));
    // step 5
    document.close();
}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createDiagnosenSheet(Patient patient, String filename, String footerText)
        throws DocumentException, IOException {

    StringBuffer sb = new StringBuffer("Diagnosen:\n");
    sb.append(patient.getDiagnosen());/*from   w w w.  j  av  a 2s  .c  o  m*/
    sb.append("\n");
    sb.append("Persnliche Anamnese:\n");
    sb.append(patient.getPersAnamnese());
    sb.append("\n");

    // step 1
    Document document = new Document(PageSize.A4);

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    //Rectangle rect = new Rectangle(30, 30, 559, 800);
    writer.setBoxSize("art", rect);

    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    event.setHeaderText(
            patient.getVorname() + " " + patient.getName() + " (" + patient.getGeburtsdatum() + ")");
    event.setFooterText(footerText);
    writer.setPageEvent(event);

    document.setMargins(36, 72, 60, 60);

    // step 3
    document.open();

    document.add(new Chunk("")); // << this will do the trick. 

    if (patient.getDiagnosen().length() > 0) {
        Paragraph p = new Paragraph("Diagnosen:", fontTimesTitle);
        p.setSpacingAfter(10f);
        document.add(p);

        String[] chunksDiag = patient.getDiagnosen().toString().split("(?m)^\\s*$");
        for (String chunk : chunksDiag) {
            document.add(new Paragraph(chunk, fontTimes));
        }
    } else {
        document.add(new Paragraph("Keine Diagnosen vorhanden", fontTimes));

    }

    if (patient.getPersAnamnese().length() > 0) {
        Paragraph p = new Paragraph("Persnliche Anamnese:", fontTimesTitle);
        p.setSpacingBefore(10f);
        p.setSpacingAfter(10f);

        document.add(p);

        String[] chunksAnam = patient.getPersAnamnese().toString().split("(?m)^\\s*$");
        for (String chunk : chunksAnam) {
            document.add(new Paragraph(chunk, fontTimes));
        }
    } else {
        document.add(new Paragraph("Keine Persnliche Anamnese vorhanden", fontTimes));

    }

    // step 5
    document.close();

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

public static void createFixMediSheet(Patient patient, String filename, String footerText)
        throws DocumentException, IOException {
    Prescription[] prescriptions = patient.getFixmedikation();
    StringBuffer sb = new StringBuffer();
    for (Prescription prescription : prescriptions) {
        //System.out.println("Prescription: " + prescription.getLabel() + "/" + prescription.getDosis());
        sb.append(prescription.getLabel());
        sb.append("\r\n");
    }//  ww  w.j av  a  2 s.c  o m

    // step 1
    Document document = new Document(PageSize.A4);

    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    //Rectangle rect = new Rectangle(30, 30, 559, 800);
    writer.setBoxSize("art", rect);

    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    event.setHeaderText(
            patient.getVorname() + " " + patient.getName() + " (" + patient.getGeburtsdatum() + ")");
    event.setFooterText(footerText);
    writer.setPageEvent(event);

    document.setMargins(36, 72, 60, 60);

    // step 3
    document.open();

    document.add(new Chunk("")); // << this will do the trick. 

    if (sb.length() > 0) {
        Paragraph p = new Paragraph("Fixmedikation:", fontTimesTitle);
        p.setSpacingAfter(10f);
        document.add(p);

        String[] chunksDiag = sb.toString().split("(?m)^\\s*$");
        for (String chunk : chunksDiag) {
            document.add(new Paragraph(chunk, fontTimes));
        }
    } else {

        //document.add(new Paragraph("Keine Medikationen vorhanden", fontTimes));
        Paragraph p = new Paragraph(new Chunk("Keine Medikationen vorhanden", fontTimesTitle));
        p.setSpacingBefore(20f);
        document.add(p);

    }

    // step 5
    document.close();

}