Example usage for org.apache.pdfbox.pdmodel PDDocument save

List of usage examples for org.apache.pdfbox.pdmodel PDDocument save

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument save.

Prototype

public void save(OutputStream output) throws IOException 

Source Link

Document

This will save the document to an output stream.

Usage

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java

License:EUPL

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {/*from ww w  . jav  a 2  s.  c  om*/
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDPage.PAGE_SIZE_A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, false, false);
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, false, false);
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);
        List<PDPage> pages = new ArrayList<PDPage>();
        visualDoc.getDocumentCatalog().getPages().getAllKids(pages);

        PDPage firstPage = pages.get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

License:EUPL

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {//from  w w  w.j a  v  a2 s  .c  om
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDRectangle.A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, pdfObject.getStatus().getSettings());
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, pdfObject.getStatus().getSettings());
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);

        PDPage firstPage = visualDoc.getDocumentCatalog().getPages().get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        int targetPageNumber = 0;//TODO: is this always the case
        PDFRenderer pdfRenderer = new PDFRenderer(visualDoc);
        BufferedImage outputImage = pdfRenderer.renderImageWithDPI(targetPageNumber, targetRes, ImageType.ARGB);

        //BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsTemplateCreator.java

License:EUPL

public InputStream buildPDF(PDFAsVisualSignatureDesigner properties, PDDocument originalDocument)
        throws IOException, PdfAsException {
    logger.debug("pdf building has been started");
    PDFTemplateStructure pdfStructure = pdfBuilder.getStructure();

    // we create array of [Text, ImageB, ImageC, ImageI]
    this.pdfBuilder.createProcSetArray();

    //create page
    this.pdfBuilder.createPage(properties);
    PDPage page = pdfStructure.getPage();

    //create template
    this.pdfBuilder.createTemplate(page);
    PDDocument template = pdfStructure.getTemplate();

    //create /AcroForm
    this.pdfBuilder.createAcroForm(template);
    PDAcroForm acroForm = pdfStructure.getAcroForm();

    // AcroForm contains singature fields
    this.pdfBuilder.createSignatureField(acroForm);
    PDSignatureField pdSignatureField = pdfStructure.getSignatureField();

    // create signature
    this.pdfBuilder.createSignature(pdSignatureField, page, properties.getSignatureFieldName());

    // that is /AcroForm/DR entry
    this.pdfBuilder.createAcroFormDictionary(acroForm, pdSignatureField);

    // create AffineTransform
    this.pdfBuilder.createAffineTransform(properties.getAffineTransformParams());
    //AffineTransform transform = pdfStructure.getAffineTransform();

    // rectangle, formatter, image. /AcroForm/DR/XObject contains that form
    this.pdfBuilder.createSignatureRectangle(pdSignatureField, properties,
            properties.getRotation() + properties.getPageRotation());
    this.pdfBuilder.createFormaterRectangle(properties.getFormaterRectangleParams());
    PDRectangle formater = pdfStructure.getFormaterRectangle();

    //this.pdfBuilder.createSignatureImage(template, properties.getImageStream());

    // create form stream, form and  resource. 
    this.pdfBuilder.createHolderFormStream(template);
    PDStream holderFormStream = pdfStructure.getHolderFormStream();
    this.pdfBuilder.createHolderFormResources();
    PDResources holderFormResources = pdfStructure.getHolderFormResources();
    this.pdfBuilder.createHolderForm(holderFormResources, holderFormStream, formater);

    // that is /AP entry the appearance dictionary.
    this.pdfBuilder.createAppearanceDictionary(pdfStructure.getHolderForm(), pdSignatureField,
            properties.getRotation() + properties.getPageRotation());

    // inner formstream, form and resource (hlder form containts inner form)
    this.pdfBuilder.createInnerFormStreamPdfAs(template, originalDocument);
    this.pdfBuilder.createInnerFormResource();
    PDResources innerFormResource = pdfStructure.getInnerFormResources();
    this.pdfBuilder.createInnerForm(innerFormResource, pdfStructure.getInnterFormStream(), formater);
    PDXObjectForm innerForm = pdfStructure.getInnerForm();

    // inner form must be in the holder form as we wrote
    this.pdfBuilder.insertInnerFormToHolerResources(innerForm, holderFormResources);

    //  Image form is in this structure: /AcroForm/DR/FRM0/Resources/XObject/n0
    //this.pdfBuilder.createImageFormStream(template);
    //PDStream imageFormStream = pdfStructure.getImageFormStream();
    //this.pdfBuilder.createImageFormResources();
    //PDResources imageFormResources = pdfStructure.getImageFormResources();
    //this.pdfBuilder.createImageForm(imageFormResources, innerFormResource, imageFormStream, formater, transform,
    //        pdfStructure.getJpedImage());

    // now inject procSetArray
    /*this.pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, imageFormResources, holderFormResources,
        pdfStructure.getProcSet());*/
    this.pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, null, holderFormResources,
            pdfStructure.getProcSet());// www. jav a2  s  . c  om

    /*String imgFormName = pdfStructure.getImageFormName();
    String imgName = pdfStructure.getImageName();*/
    String innerFormName = pdfStructure.getInnerFormName();

    // now create Streams of AP
    /*this.pdfBuilder.injectAppearanceStreams(holderFormStream, imageFormStream, imageFormStream, imgFormName,
        imgName, innerFormName, properties);*/
    this.pdfBuilder.injectAppearanceStreams(holderFormStream, null, null, null, null, innerFormName,
            properties);
    this.pdfBuilder.createVisualSignature(template);
    this.pdfBuilder.createWidgetDictionary(pdSignatureField, holderFormResources);

    ByteArrayInputStream in = null;
    try {
        //COSDocument doc = pdfStructure.getVisualSignature();
        //doc.
        //in = pdfStructure.getTemplateAppearanceStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        template.save(baos);
        baos.close();
        in = new ByteArrayInputStream(baos.toByteArray());
    } catch (COSVisitorException e) {
        logger.warn("COSVisitorException: can't get apereance stream ", e);
    }
    logger.debug("stream returning started, size= " + in.available());

    // we must close the document
    this.pdfBuilder.closeTemplate(template);

    // return result of the stream 
    return in;
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsTemplateCreator.java

License:EUPL

public InputStream buildPDF(PDFAsVisualSignatureDesigner properties, PDDocument originalDocument)
        throws IOException, PdfAsException {
    logger.debug("pdf building has been started");
    PDFTemplateStructure pdfStructure = pdfBuilder.getStructure();

    // we create array of [Text, ImageB, ImageC, ImageI]
    this.pdfBuilder.createProcSetArray();

    //create page
    this.pdfBuilder.createPage(properties);
    PDPage page = pdfStructure.getPage();

    //create template
    this.pdfBuilder.createTemplate(page);
    PDDocument template = pdfStructure.getTemplate();

    //create /AcroForm
    this.pdfBuilder.createAcroForm(template);
    PDAcroForm acroForm = pdfStructure.getAcroForm();

    // AcroForm contains singature fields
    this.pdfBuilder.createSignatureField(acroForm);
    PDSignatureField pdSignatureField = pdfStructure.getSignatureField();

    // create signature
    this.pdfBuilder.createSignature(pdSignatureField, page, properties.getSignatureFieldName());

    // that is /AcroForm/DR entry
    this.pdfBuilder.createAcroFormDictionary(acroForm, pdSignatureField);

    // create AffineTransform
    this.pdfBuilder.createAffineTransform(properties.getAffineTransformParams());
    //AffineTransform transform = pdfStructure.getAffineTransform();

    // rectangle, formatter, image. /AcroForm/DR/XObject contains that form
    this.pdfBuilder.createSignatureRectangle(pdSignatureField, properties,
            properties.getRotation() + properties.getPageRotation());
    this.pdfBuilder.createFormaterRectangle(properties.getFormaterRectangleParams());
    PDRectangle formater = pdfStructure.getFormatterRectangle();

    //this.pdfBuilder.createSignatureImage(template, properties.getImageStream());

    // create form stream, form and  resource. 
    this.pdfBuilder.createHolderFormStream(template);
    PDStream holderFormStream = pdfStructure.getHolderFormStream();
    this.pdfBuilder.createHolderFormResources();
    PDResources holderFormResources = pdfStructure.getHolderFormResources();
    this.pdfBuilder.createHolderForm(holderFormResources, holderFormStream, formater);

    // that is /AP entry the appearance dictionary.
    this.pdfBuilder.createAppearanceDictionary(pdfStructure.getHolderForm(), pdSignatureField,
            properties.getRotation() + properties.getPageRotation());

    // inner formstream, form and resource (hlder form containts inner form)
    this.pdfBuilder.createInnerFormStreamPdfAs(template, originalDocument);
    this.pdfBuilder.createInnerFormResource();
    PDResources innerFormResource = pdfStructure.getInnerFormResources();
    this.pdfBuilder.createInnerForm(innerFormResource, pdfStructure.getInnerFormStream(), formater);
    PDFormXObject innerForm = pdfStructure.getInnerForm();

    // inner form must be in the holder form as we wrote
    this.pdfBuilder.insertInnerFormToHolerResources(innerForm, holderFormResources);

    //  Image form is in this structure: /AcroForm/DR/FRM0/Resources/XObject/n0
    //this.pdfBuilder.createImageFormStream(template);
    //PDStream imageFormStream = pdfStructure.getImageFormStream();
    //this.pdfBuilder.createImageFormResources();
    //PDResources imageFormResources = pdfStructure.getImageFormResources();
    //this.pdfBuilder.createImageForm(imageFormResources, innerFormResource, imageFormStream, formater, transform,
    //        pdfStructure.getJpedImage());

    // now inject procSetArray
    /*this.pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, imageFormResources, holderFormResources,
        pdfStructure.getProcSet());*/
    this.pdfBuilder.injectProcSetArray(innerForm, page, innerFormResource, null, holderFormResources,
            pdfStructure.getProcSet());//  ww  w .j  a v  a 2 s . c  o m

    /*String imgFormName = pdfStructure.getImageFormName();
    String imgName = pdfStructure.getImageName();*/
    String innerFormName = pdfStructure.getInnerFormName().getName();

    // now create Streams of AP
    /*this.pdfBuilder.injectAppearanceStreams(holderFormStream, imageFormStream, imageFormStream, imgFormName,
        imgName, innerFormName, properties);*/
    this.pdfBuilder.injectAppearanceStreams(holderFormStream, null, null, null, null, innerFormName,
            properties);
    this.pdfBuilder.createVisualSignature(template);
    this.pdfBuilder.createWidgetDictionary(pdSignatureField, holderFormResources);

    ByteArrayInputStream in = null;

    //COSDocument doc = pdfStructure.getVisualSignature();
    //doc.
    //in = pdfStructure.getTemplateAppearanceStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    template.save(baos);
    baos.close();

    SignatureProfileSettings signatureProfileSettings = this.pdfBuilder.signatureProfileSettings;

    boolean requirePDFA3 = signatureProfileSettings.isPDFA3();

    if (requirePDFA3) {

        //FileOutputStream fos = new FileOutputStream("/tmp/signature.pdf");
        //fos.write(baos.toByteArray());
        //fos.close();

        PDDocument cidSetRemoved = PDDocument.load(baos.toByteArray());
        try {
            this.pdfBuilder.removeCidSet(cidSetRemoved);
            baos.reset();
            baos = new ByteArrayOutputStream();
            cidSetRemoved.save(baos);
            baos.close();
        } finally {
            cidSetRemoved.close();
        }
    }

    in = new ByteArrayInputStream(baos.toByteArray());

    logger.debug("stream returning started, size= " + in.available());

    // we must close the document
    this.pdfBuilder.closeTemplate(template);

    // return result of the stream 
    return in;
}

From source file:at.medevit.elexis.impfplan.ui.handlers.PrintVaccinationEntriesHandler.java

License:Open Source License

private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
    PDDocumentInformation pdi = new PDDocumentInformation();
    Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
    pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
    pdi.setCreationDate(new GregorianCalendar());
    pdi.setTitle("Impfausweis " + patient.getLabel());

    PDDocument document = new PDDocument();
    document.setDocumentInformation(pdi);

    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    document.addPage(page);/*from www .  jav a  2 s .  co  m*/

    PDRectangle pageSize = page.findMediaBox();
    PDFont font = PDType1Font.HELVETICA_BOLD;

    PDFont subFont = PDType1Font.HELVETICA;

    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.setFont(font, 14);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
    contentStream.drawString(patient.getLabel());
    contentStream.endText();

    String dateLabel = sdf.format(Calendar.getInstance().getTime());
    String title = Person.load(mandant.getId()).get(Person.TITLE);
    String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
    contentStream.beginText();
    contentStream.setFont(subFont, 10);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
    contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
    contentStream.endText();

    BufferedImage imageAwt = convertToAWT(image.getImageData());

    PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
    contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
    contentStream.close();

    String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR,
            CoreHub.getWritableUserDir().getAbsolutePath());
    if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
        SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath
                + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
    }
    File outputDir = new File(outputPath);
    File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
    document.save(pdf);
    document.close();
    Desktop.getDesktop().open(pdf);
}

From source file:at.oculus.teamf.technical.printing.Printer.java

License:Open Source License

/**
 * <h3>$print</h3>/*  w w w.java2s .  c om*/
 * <p/>
 * <b>Description:</b>
 * <p/>
 * This method prints the given parameters into a PDF-Document and opens the file with the standard program.
 * <p/>
 * <b>Parameter</b>
 *
 * @param title Is a string which will be printed as title in the PDF Document.
 * @param text Is a string which will be printed as message in the PDF Document.
 */
public void print(String title, String text) throws IOException, COSVisitorException {

    //creates a new PDDocument object
    PDDocument document = new PDDocument();
    //create a page to the document
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    //rectangle is for sizes (height and width) of page
    PDRectangle rectangle = page1.getMediaBox();
    //add page to document
    document.addPage(page1);

    //fonts for the document are implemented here
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    //running variable to calculate which line you are in the document right now
    int line = 0;

    try {
        //create the content stream which will write into the document
        PDPageContentStream stream = new PDPageContentStream(document, page1);

        //always use all these lines for entering new text into the document
        //move textToPosition will set the cursor to the current position
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT, rectangle.getHeight() - SPACING_TOP);
        stream.drawString(title + ":");
        stream.endText();

        //calculates the correct place and then writes the whole text into the PDF-Document
        int start = 0;
        int end = text.length();
        while (start < end) {
            String tobePrinted;
            if ((end - start) > MAX_CHARACTERS_PER_LINE) {
                int tempEnd = start + MAX_CHARACTERS_PER_LINE;
                while (text.charAt(tempEnd) != ' ') {
                    ++tempEnd;
                }
                tobePrinted = text.substring(start, start = ++tempEnd);

            } else {
                tobePrinted = text.substring(start);
                start = start + MAX_CHARACTERS_PER_LINE;
            }
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(tobePrinted);
            stream.endText();

        }
        //print oculus image into pdf file
        BufferedImage awtImage = ImageIO
                .read(new File("/home/oculus/IdeaProjects/Oculus/Technical/src/res/oculus.JPG"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 0.3f; // alter this value to set the image size
        stream.drawXObject(ximage, 380, 780, ximage.getWidth() * scale, ximage.getHeight() * scale);

        //close stream afterwards
        stream.close();

        //save document and close document
        document.save(
                "/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/"
                        + title + ".pdf");
        document.close();
        //open document with standard application for the file
        Desktop.getDesktop().open(new File(
                "/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/"
                        + title + ".pdf"));
    } catch (IOException | COSVisitorException e) {
        throw e;
    }
}

From source file:at.oculus.teamf.technical.printing.Printer.java

License:Open Source License

/**
 * <h3>$printPrescription</h3>
 * <p/>/*w ww .j  a  va 2 s  . com*/
 * <b>Description:</b>
 * <p/>
 * This method prints the given parameters into a PDF-Document and opens the file with the standard program.
 * <p/>
 * <b>Parameter</b>
 *
 * @param iPrescription Is an Interface of a prescription from which all the information will be printed into
 *                      a PDF-File and then started with standard application from OS.
 */
public void printPrescription(IPrescription iPrescription, IDoctor iDoctor) throws COSVisitorException,
        IOException, CantGetPresciptionEntriesException, NoPrescriptionToPrintException {
    if (iPrescription == null) {
        throw new NoPrescriptionToPrintException();
    }

    //instantiate a new document, create a page and add the page to the document
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    PDRectangle rectangle = page1.getMediaBox();
    document.addPage(page1);

    //create fonts for the document
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    //running variable to calculate current line
    int line = 0;

    try {
        //new Stream to print into the file
        PDPageContentStream stream = new PDPageContentStream(document, page1);

        //print header (headlining)
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT, rectangle.getHeight() - SPACING_TOP);
        stream.drawString("Prescription:");
        stream.endText();

        //get patient to print data from
        IPatient iPatient = iPrescription.getPatient();

        //write data from patient
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iPatient.getFirstName() + " " + iPatient.getLastName());
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        /* -- Team D: Add check on null -- */
        stream.drawString(iPatient.getBirthDay() == null ? "" : iPatient.getBirthDay().toString());
        /* -- -- -- */
        stream.endText();

        if (iPatient.getStreet() != null) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getStreet());
            stream.endText();
        }

        if ((iPatient.getPostalCode() != null) && (iPatient.getCity() != null)) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getPostalCode() + ", " + iPatient.getCity());
            stream.endText();
        }

        //next row
        ++line;

        //write data from doctor
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Prescription issued from doctor:");
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iDoctor.getTitle() + " " + iDoctor.getFirstName() + " " + iDoctor.getLastName());
        stream.endText();

        //next row
        ++line;

        //print all the entries in the prescription
        if (iPrescription.getPrescriptionEntries().size() > 0) {
            stream.beginText();
            stream.setFont(fontBold, 14);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString("Prescription Entries:");
            stream.endText();
            for (IPrescriptionEntry entry : iPrescription.getPrescriptionEntries()) {
                stream.beginText();
                stream.setFont(fontPlain, 12);
                stream.moveTextPositionByAmount(SPACING_LEFT,
                        rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
                stream.drawString("ID: " + entry.getId() + ", " + entry.getMedicine());
                stream.endText();
            }
        }

        //print oculus image into pdf file
        //Not working
        /*BufferedImage awtImage = ImageIO.read(new File("oculus.JPG"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 0.3f; // alter this value to set the image size
        stream.drawXObject(ximage, 380, 780, ximage.getWidth() * scale, ximage.getHeight() * scale);*/

        //signature field

        ++line;
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Doctor's Signature:");
        stream.endText();

        //print a line for signature field
        stream.setLineWidth(0.5f);
        stream.addLine(SPACING_LEFT, rectangle.getHeight() - LINE_HEIGHT * (line += 2) - SPACING_HEADER,
                SPACING_LEFT + 100, rectangle.getHeight() - LINE_HEIGHT * (line) - SPACING_HEADER);
        stream.closeAndStroke();

        //close the stream
        stream.close();

        //save the document and close it
        document.save("prescription.pdf"); //Todo: position from property file
        document.close();
        //open file with standard OS application
        Desktop.getDesktop().open(new File("prescription.pdf"));

        //Print file directly from standard printer (NOT SUPPORTED ON OCULUS-LINUX -- should be tested first!!!)
        //Desktop.getDesktop().print(new File("/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/prescription.pdf"));
    } catch (COSVisitorException | CantGetPresciptionEntriesException | IOException e) {
        throw e;
    }
}

From source file:au.org.alfred.icu.pdf.services.dischargesummary.pdfservice.java

public String dischargeToCerner(@WebParam(name = "parameters") String parameters) {

    PDDocument pdf;
    String encodedPdf = "Error";
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String pdfName = "Error Could Not Create File";
    try {/*  w w w. ja  v  a2  s  .co  m*/
        pdf = new PDDocument();
        JSONObject jsonParams = new JSONObject(parameters);

        String title = jsonParams.getString("pmiid");
        String subject = jsonParams.getString("admid");
        String keywords = jsonParams.getString("admid");
        String creator = jsonParams.getString("user");
        String author = jsonParams.getString("user");
        ICUDischargeSummaryFactory.addDocumentInformation(pdf, title, subject, keywords, creator, author);
        pdfName = ICUDischargeSummaryFactory.createContent(pdf, jsonParams.getString("icuid"),
                jsonParams.getString("admid"), jsonParams.getString("pmiid"), jsonParams.getString("user"),
                jsonParams.getString("userid"));

        pdf.save(output);
        String user = "desousami";
        String passwd = "bkdr4ICUm3k";
        String domain = "BAYSIDEHEALTH";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, passwd);
        String path = "smb://alfapps01/apps/ICUApps/CernerDischarge/" + pdfName;
        SmbFile sFile = new SmbFile(path, auth);
        SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
        sfos.write(output.toByteArray());
        output.close();
        pdf.close();

    } catch (IOException ex) {
        ex.printStackTrace(System.out);
        Logger.getLogger(pdfservice.class.getName()).log(Level.SEVERE, null, ex);
    } catch (COSVisitorException ex) {
        Logger.getLogger(pdfservice.class.getName()).log(Level.SEVERE, null, ex);
    }

    return pdfName;
}

From source file:au.org.alfred.icu.pdf.services.factories.ICUDischargeSummaryFactory.java

public static void saveDocument(String path, PDDocument pdf) throws IOException, COSVisitorException {
    //System.out.println(path);
    pdf.save(path);

}

From source file:blankpdf.BlankPDF.java

public void TestePDF() {
    String fileName = "Sparta.pdf"; // name of our file

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();

    doc.addPage(page);//from ww w  . j a v a2 s  .c  om
    PDImageXObject imagem;
    PDPageContentStream content;
    try {
        content = new PDPageContentStream(doc, page);

        //OBSERVAO IMPORTANTE --
        //Para funcionar sem tratamento de string criar o projeto em pasta sem caracteres
        //especiais nem ESPAO EM BRANCO
        imagem = PDImageXObject.createFromFile(getClass().getResource("sparta.png").getPath(), doc);
        ///Users/marcelosiedler/Google%20Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/silviosantos.jpg
        //imagem = PDImageXObject.createFromFile("/Users/marcelosiedler/Google Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/sparta.png", doc);

        content.beginText();
        content.setFont(PDType1Font.TIMES_BOLD, 26);
        content.newLineAtOffset(10, 750);
        content.showText("Gincana IFSUL2");
        content.endText();

        content.beginText();
        content.setFont(PDType1Font.TIMES_BOLD, 16);
        content.newLineAtOffset(80, 700);
        content.showText("Turma : ");
        content.endText();

        content.drawImage(imagem, 75, 500);

        content.close();
        doc.save(fileName);
        doc.close();

        System.out.println("Arquivo criado em : " + System.getProperty("user.dir"));

    } catch (Exception e) {

        System.out.println(e.getMessage());

    }

}