Example usage for com.itextpdf.text PageSize A4

List of usage examples for com.itextpdf.text PageSize A4

Introduction

In this page you can find the example usage for com.itextpdf.text PageSize A4.

Prototype

Rectangle A4

To view the source code for com.itextpdf.text PageSize A4.

Click Source Link

Document

This is the a4 format

Usage

From source file:com.netsteadfast.greenstep.bsc.command.KpiReportPdfCommand.java

License:Apache License

private String createPdf(Context context) throws Exception {
    BscReportPropertyUtils.loadData();//  w  w  w . j  a  v  a  2  s .  c  o m
    BscReportSupportUtils.loadExpression(); // 2015-04-18 add
    String visionOid = (String) context.get("visionOid");
    VisionVO vision = null;
    BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context);
    for (VisionVO visionObj : treeObj.getVisions()) {
        if (visionObj.getOid().equals(visionOid)) {
            vision = visionObj;
        }
    }
    FontFactory.register(BscConstants.PDF_ITEXT_FONT);
    String fileName = UUID.randomUUID().toString() + ".pdf";
    String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
    OutputStream os = new FileOutputStream(fileFullPath);
    //Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    document.left(100f);
    document.top(150f);
    PdfWriter writer = PdfWriter.getInstance(document, os);
    document.open();

    int dateRangeRows = 4 + vision.getPerspectives().get(0).getObjectives().get(0).getKpis().get(0)
            .getDateRangeScores().size();
    PdfPTable table = new PdfPTable(MAX_COLSPAN);
    PdfPTable dateRangeTable = new PdfPTable(dateRangeRows);
    PdfPTable chartsTable = new PdfPTable(2);
    PdfPTable signTable = new PdfPTable(1);
    table.setWidthPercentage(100f);
    dateRangeTable.setWidthPercentage(100f);
    chartsTable.setWidthPercentage(100f);
    signTable.setWidthPercentage(100f);

    this.createHead(table, vision);
    this.createBody(table, vision);
    this.createDateRange(dateRangeTable, vision, context, dateRangeRows);
    this.putCharts(chartsTable, context);
    this.putSignature(signTable, context);

    document.add(chartsTable);
    document.add(table);
    document.add(dateRangeTable);
    document.add(signTable);
    document.close();
    writer.close();

    os.flush();
    os.close();
    os = null;

    File file = new File(fileFullPath);
    String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file,
            "kpi-report.pdf");
    file = null;
    return oid;
}

From source file:com.netsteadfast.greenstep.bsc.command.OrganizationReportPdfCommand.java

License:Apache License

private String createPdf(Context context) throws Exception {
    BscReportPropertyUtils.loadData();/*  w  ww  . java 2  s.  c  o m*/
    String visionOid = (String) context.get("visionOid");
    VisionVO vision = null;
    BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context);
    for (VisionVO visionObj : treeObj.getVisions()) {
        if (visionObj.getOid().equals(visionOid)) {
            vision = visionObj;
        }
    }
    FontFactory.register(BscConstants.PDF_ITEXT_FONT);
    String fileName = UUID.randomUUID().toString() + ".pdf";
    String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
    OutputStream os = new FileOutputStream(fileFullPath);
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    document.left(100f);
    document.top(150f);
    PdfWriter writer = PdfWriter.getInstance(document, os);
    document.open();

    PdfPTable table = new PdfPTable(MAX_COLSPAN);
    table.setWidthPercentage(100f);
    PdfPTable signTable = new PdfPTable(1);
    signTable.setWidthPercentage(100f);

    this.createHead(table, vision, context);
    this.createBody(table, vision);

    this.putSignature(signTable, context);

    document.add(table);
    document.add(signTable);
    document.close();
    writer.close();

    os.flush();
    os.close();
    os = null;

    File file = new File(fileFullPath);
    String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file,
            "department-report.pdf");
    file = null;
    return oid;
}

From source file:com.netsteadfast.greenstep.bsc.command.PersonalReportPdfCommand.java

License:Apache License

private String createPdf(Context context) throws Exception {
    BscReportPropertyUtils.loadData();/*  w w  w . j a  v  a  2  s  .c  om*/
    String visionOid = (String) context.get("visionOid");
    VisionVO vision = null;
    BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context);
    for (VisionVO visionObj : treeObj.getVisions()) {
        if (visionObj.getOid().equals(visionOid)) {
            vision = visionObj;
        }
    }
    FontFactory.register(BscConstants.PDF_ITEXT_FONT);
    String fileName = UUID.randomUUID().toString() + ".pdf";
    String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
    OutputStream os = new FileOutputStream(fileFullPath);
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    document.left(100f);
    document.top(150f);
    PdfWriter writer = PdfWriter.getInstance(document, os);
    document.open();

    PdfPTable table = new PdfPTable(MAX_COLSPAN);
    table.setWidthPercentage(100f);
    PdfPTable signTable = new PdfPTable(1);
    signTable.setWidthPercentage(100f);

    this.createHead(table, vision, context);
    this.createBody(table, vision);
    this.createFoot(table, context);
    this.putSignature(signTable, context);

    document.add(table);
    document.add(signTable);
    document.close();
    writer.close();

    os.flush();
    os.close();
    os = null;

    File file = new File(fileFullPath);
    String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file,
            "personal-report.pdf");
    file = null;
    return oid;
}

From source file:com.pablog178.pdfcreator.android.PdfcreatorModule.java

License:Open Source License

private void generateiTextPDFfunction(HashMap args) {
    if (args.containsKey("fileName")) {
        Object fileName = args.get("fileName");
        if (fileName instanceof String) {
            this.fileName = (String) fileName;
            Log.i(PROXY_NAME, "fileName: " + this.fileName);
        }/*from  w  ww  .j a  v  a  2 s. c o  m*/
    } else
        return;

    if (args.containsKey("view")) {
        Object viewObject = args.get("view");
        if (viewObject instanceof TiViewProxy) {
            TiViewProxy viewProxy = (TiViewProxy) viewObject;
            this.view = viewProxy.getOrCreateView();
            if (this.view == null) {
                Log.e(PROXY_NAME, "NO VIEW was created!!");
                return;
            }
            Log.i(PROXY_NAME, "view: " + this.view.toString());
        }
    } else
        return;

    if (args.containsKey("quality")) {
        this.quality = TiConvert.toInt(args.get("quality"));
    }

    if (args.containsKey("pageSize")) {
        Object pageSize = args.get("pageSize");
        if (pageSize instanceof String) {
            if (pageSize.equals("letter")) {
                this.pageSize = PageSize.LETTER;
            } else if (pageSize.equals("A4")) {
                this.pageSize = PageSize.A4;
            } else {
                this.pageSize = PageSize.LETTER;
            }
        }
    }

    TiBaseFile file = TiFileFactory.createTitaniumFile(this.fileName, true);
    Log.i(PROXY_NAME, "file full path: " + file.nativePath());
    try {

        Resources appResources = app.getResources();
        OutputStream outputStream = file.getOutputStream();
        final int MARGIN = 0;
        final float PDF_WIDTH = this.pageSize.getWidth() - MARGIN * 2; // A4: 595 //Letter: 612
        final float PDF_HEIGHT = this.pageSize.getHeight() - MARGIN * 2; // A4: 842 //Letter: 792
        final int DEFAULT_VIEW_WIDTH = 980;
        final int DEFAULT_VIEW_HEIGHT = 1384;
        int viewWidth = DEFAULT_VIEW_WIDTH;
        int viewHeight = DEFAULT_VIEW_HEIGHT;

        Document pdfDocument = new Document(this.pageSize, MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);

        Log.i(PROXY_NAME, "PDF_WIDTH: " + PDF_WIDTH);
        Log.i(PROXY_NAME, "PDF_HEIGHT: " + PDF_HEIGHT);

        WebView view = (WebView) this.view.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = DEFAULT_VIEW_WIDTH;
            }

            if (viewHeight <= 0) {
                viewHeight = DEFAULT_VIEW_HEIGHT;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
            viewWidth = DEFAULT_VIEW_WIDTH;
            viewHeight = DEFAULT_VIEW_HEIGHT;
        }

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Log.i(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.i(PROXY_NAME, "viewHeight: " + viewHeight);

        float scaleFactorWidth = 1 / ((float) viewWidth / PDF_WIDTH);
        float scaleFactorHeight = 1 / ((float) viewHeight / PDF_HEIGHT);

        Log.i(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.i(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);

        // Paint paintAntialias = new Paint();
        // paintAntialias.setAntiAlias(true);
        // paintAntialias.setFilterBitmap(true);

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(viewCanvas);
        } else {
            viewCanvas.drawColor(Color.WHITE);
        }
        view.draw(viewCanvas);

        TiBaseFile pdfImg = createTempFile();

        // ByteArrayOutputStream stream = new ByteArrayOutputStream(32);
        // viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, stream);
        viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, pdfImg.getOutputStream());

        FileInputStream pdfImgInputStream = new FileInputStream(pdfImg.getNativeFile());
        byte[] pdfImgBytes = IOUtils.toByteArray(pdfImgInputStream);
        pdfImgInputStream.close();

        // ByteBuffer      buffer         = ByteBuffer.allocate(viewBitmap.getByteCount());
        // viewBitmap.copyPixelsToBuffer(buffer);

        pdfDocument.open();
        float yFactor = viewHeight * scaleFactorWidth;
        int pageNumber = 1;

        do {
            if (pageNumber > 1) {
                pdfDocument.newPage();
            }
            pageNumber++;
            yFactor -= PDF_HEIGHT;

            Image pageImage = Image.getInstance(pdfImgBytes, true);
            // Image pageImage = Image.getInstance(buffer.array());
            pageImage.scalePercent(scaleFactorWidth * 100);
            pageImage.setAbsolutePosition(0f, -yFactor);
            pdfDocument.add(pageImage);

            Log.i(PROXY_NAME, "yFactor: " + yFactor);
        } while (yFactor > 0);

        pdfDocument.close();

        sendCompleteEvent();

    } catch (Exception exception) {
        Log.e(PROXY_NAME, "Error: " + exception.toString());
        sendErrorEvent(exception.toString());
    }
}

From source file:com.pdi.util.PdfGenerator.java

public static void generarPresupuesto(String lugar, Date fecha, float cantidad, String tipo, Cliente cliente,
        float precio, Aliado aliado, String path) {

    try {//from   w w w.  j a va2  s  .  co m

        NEGRITA_12_VERDE.setColor(145, 189, 57);

        long miliSemana = System.currentTimeMillis() + (86400 * 7 * 1000);
        Date vtoPresup = new Date(miliSemana);
        float precioPers = precio / cantidad;
        int precioTotalInt = Math.round(precio);
        int precioPersInt = Math.round(precioPers);
        int cantPersonasInt = Math.round(cantidad);

        //Referencia al objeto Doc
        Document document = new Document(PageSize.A4, //Dimensiones
                36, //margIzq
                36, //margDer
                36, //margenSup
                36); // margenInf

        //Creamos el archivo fisico
        FileOutputStream salida = new FileOutputStream(path);

        //Referencia e inicializacion del objeto que "escribe" el PDF
        PdfWriter writer = PdfWriter.getInstance(document, salida);
        writer.setInitialLeading(0);

        //Imagen Logo
        Image logoPDI = Image.getInstance("Logo PDI.png");
        logoPDI.scaleToFit(215, 205);
        logoPDI.setAlignment(Chunk.ALIGN_LEFT);
        //image.setAbsolutePosition(200, 200);

        //Imagen QR
        Image qr = Image.getInstance("QR PDI.png");
        qr.scaleToFit(211, 165);
        qr.setAbsolutePosition(295, PageSize.A4.getHeight() - 390);

        //Parrafo info evento
        Paragraph infoEvento = new Paragraph();
        infoEvento.add(new Chunk("Informacin del Evento", NEGRITA_SUB_12));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.add(negritaNormal("Solicitante: ", cliente.toString()));
        infoEvento.add(negritaNormal("Evento: ", tipo));
        infoEvento.add(negritaNormal("Cantidad de personas: ", Integer.toString(cantPersonasInt)));
        infoEvento.add(negritaNormal("Fecha: ", General.formatoFecha.format(fecha)));
        infoEvento.add(negritaNormal("Lugar:  ", lugar));
        infoEvento.add(Chunk.NEWLINE);
        infoEvento.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Modalidad del Servicio
        Paragraph modalidadServicio = new Paragraph();
        modalidadServicio.add(new Chunk("Modalidad Servicio Integral", NEGRITA_SUB_12));
        modalidadServicio.add(Chunk.NEWLINE);
        modalidadServicio.add(new Chunk("Nuestro servicio incluye la totalidad de lo referido a"
                + " los elementos necesarios para el despacho de bebidas: Barras, Bartenders,"
                + " Artculos de Coctelera, Insumos de calidad para los tragos y Mucha Buena Onda."
                + " Con esta modalidad aseguramos la expedicin de "
                + "los tragos desde las 00hs hasta las 05hs, para que se desentiendan del asunto "
                + "y disfruten al mximo.", NORMAL_12));
        modalidadServicio.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Ver Carta
        Paragraph verCarta = new Paragraph();
        verCarta.add(negritaNormal("\u2022 Carta de Tragos: ", "Ver archivo adjunto."));
        verCarta.setIndentationLeft(20);
        verCarta.add(Chunk.NEWLINE);
        verCarta.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Titulo Info Contratacion
        Paragraph infoContratacionTitulo = new Paragraph();
        infoContratacionTitulo.add(new Chunk("Informacin de Contratacin", NEGRITA_SUB_12));
        infoContratacionTitulo.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Inf de Contratacion
        Paragraph infoContratacion = new Paragraph();
        infoContratacion.add(negritaNormal("\u2022 Mtodo de contratacin y reserva de la fecha: ",
                "A travs de contrato firmado por ambas partes. "));
        Phrase lineaCosto = new Phrase();
        lineaCosto.add(new Chunk("\u2022 Costo: ", NEGRITA_12));
        lineaCosto.add(new Chunk("$" + Integer.toString(precioPersInt) + " ", NEGRITA_14));
        lineaCosto.add(new Chunk("por persona ", NEGRITA_12));
        lineaCosto.add(new Chunk("(Total: $" + Integer.toString(precioTotalInt) + ")", NEGRITA_14));
        infoContratacion.add(lineaCosto);
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.add(negritaNormal("\u2022 Forma de Pago : ",
                "50% al momento de la firma del contrato y 50% como mximo una semana antes del evento. "));
        infoContratacion.add(Chunk.NEWLINE);
        infoContratacion.setIndentationLeft(20);
        infoContratacion.setFirstLineIndent(0);
        infoContratacion.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Despedida
        Paragraph despedida = new Paragraph();
        despedida.add(new Phrase("Quedamos al aguardo de tus comentarios,", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(new Phrase("Muchas Gracias.", NEGRITA_14));
        despedida.add(Chunk.NEWLINE);
        despedida.add(Chunk.NEWLINE);
        despedida.setAlignment(Paragraph.ALIGN_LEFT);

        //Parrafo Firma
        Paragraph firma = new Paragraph();
        firma.add(new Phrase("Piel de Iguana Tragos.-", NEGRITA_CUR_14));
        firma.add(Chunk.NEWLINE);
        firma.add(new Phrase("Cel.: 3462-15337860", NEGRITA_12_VERDE));
        firma.setAlignment(Paragraph.ALIGN_RIGHT);

        float llxLink = 279;
        float llyLink = PageSize.A4.getHeight() - 145;
        float anchoLink = 199;
        float altoLink = 16;

        //Link al facebook
        URL urlPDI = new URL("https://www.facebook.com/pieldeiguanatragos.vt");
        PdfAction irAlFace = new PdfAction(urlPDI);
        Rectangle linkLocation = new Rectangle(llxLink, llyLink, llxLink + anchoLink, llyLink + altoLink);
        PdfAnnotation link = PdfAnnotation.createLink(writer, linkLocation, PdfAnnotation.HIGHLIGHT_NONE,
                irAlFace);
        link.setBorder(new PdfBorderArray(0, 0, 0));
        writer.addAnnotation(link);

        //Espacios Vacios
        Paragraph dosEspacios = new Paragraph();
        dosEspacios.add(Chunk.NEWLINE);
        dosEspacios.add(Chunk.NEWLINE);

        //Hay que abrir el Documento, llenarlo con los elemntos creados
        //en el orden que queremos y cerrarlo
        document.open();

        PdfContentByte cb = writer.getDirectContent();

        ColumnText ct = new ColumnText(cb);
        Phrase recuadro = new Phrase();
        recuadro.add(new Chunk("Piel de Iguana Tragos", NEGRITA_SUB_14));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Servicio de tragos para eventos", NEGRITA_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("\"Piel de Iguana, para que tu noche nica sea inigualable.\"", NORMAL_CUR_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        Image logoFB = Image.getInstance("Icono FB.png");
        logoFB.scaleToFit(13, 13);
        recuadro.add(new Chunk(logoFB, 0, -3));
        recuadro.add(new Chunk("/pieldeiguanatragos.vt  -> Click Aqu!", NORMAL_12));
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(Chunk.NEWLINE);
        recuadro.add(new Chunk("Vencimiento del Prepuesto " + General.formatoFecha.format(vtoPresup),
                NORMAL_SUB_12));

        float llx = 279;
        float lly = PageSize.A4.getHeight() - 185;
        float ancho = 228;
        float alto = 150;

        ct.setSimpleColumn(recuadro, //Texto
                llx, //punta inf izquierda (x)
                lly, //punta inf izquierda (y) PageSize.A4.getHeight() - 185
                llx + ancho, //ancho del cuadro
                lly + alto, // alto del cuadro
                15, //espaciado
                Element.ALIGN_LEFT // Alineacion
        );

        ct.go();

        document.add(logoPDI);
        document.add(qr);
        document.add(dosEspacios);
        document.add(infoEvento);
        document.add(modalidadServicio);
        document.add(verCarta);
        document.add(infoContratacionTitulo);
        document.add(infoContratacion);
        document.add(despedida);
        document.add(firma);
        document.close();
        System.out.println("Archivo creado");
        int rta = JOptionPane.showConfirmDialog(VentanaMaestra.eventosCurrent,
                "Se guard el presupesto en:\n" + path + "\nDesea abrirlo?", "Presupuesto guardado",
                JOptionPane.YES_NO_OPTION);

        if (rta == JOptionPane.YES_OPTION) {
            if (Desktop.isDesktopSupported()) {
                try {
                    File myFile = new File(path);
                    Desktop.getDesktop().open(myFile);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                            "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                            "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(VentanaMaestra.eventosCurrent,
                        "No se puede abrir el archivo. Ubiquelo en su equipo" + "y abralo manualmente.",
                        "Error al abrir el archivo", JOptionPane.ERROR_MESSAGE);
            }

        }

    } catch (FileNotFoundException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (DocumentException ex) {
        System.out.println("Error: " + ex.toString());
    } catch (IOException ex) {
        System.out.println("Error: " + ex.toString());
    }

}

From source file:com.primeleaf.krystal.util.PDFConverter.java

License:Open Source License

public File getConvertedFile(DocumentRevision documentRevision, Document document, String password)
        throws Exception {
    File tempFile = documentRevision.getDocumentFile();
    if ("TIF".equalsIgnoreCase(document.getExtension()) || "TIFF".equalsIgnoreCase(document.getExtension())) {
        try {//  w  w w. j  a  v  a  2s. c o  m
            tempFile = File.createTempFile("temp", ".PDF");
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document();
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.setMargins(0, 0, 0, 0);
            FileInputStream fis = new FileInputStream(documentRevision.getDocumentFile());
            RandomAccessFileOrArray file = new RandomAccessFileOrArray(fis);
            int pages = TiffImage.getNumberOfPages(file);
            for (int page = 1; page <= pages; page++) {
                Image img = TiffImage.getTiffImage(file, page);
                img.setAbsolutePosition(0f, 0f);
                img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
                pdf.setMargins(0, 0, 0, 0);
                pdf.add(img);
                pdf.newPage();
            }
            fis.close();
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert TIFF Document to PDF");
        }
    } else if ("JPG".equalsIgnoreCase(document.getExtension())
            || "JPEG".equalsIgnoreCase(document.getExtension())
            || "PNG".equalsIgnoreCase(document.getExtension())
            || "BMP".equalsIgnoreCase(document.getExtension())
            || "GIF".equalsIgnoreCase(document.getExtension())) {
        try {
            tempFile = File.createTempFile("temp", ".PDF");
            Image img = Image.getInstance(documentRevision.getDocumentFile().getAbsolutePath());
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document(
                    new Rectangle(img.getWidth(), img.getHeight()), 0, 0, 0, 0);
            img.setAbsolutePosition(0f, 0f);
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.add(img);
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert Image Document to PDF");
        }
    } else if ("PDF".equalsIgnoreCase(document.getExtension())) {
        tempFile = documentRevision.getDocumentFile();
    } else {
        String tempFilePath = "";
        String KRYSTAL_HOME = System.getProperty("krystal.home");
        if (KRYSTAL_HOME == null) {
            KRYSTAL_HOME = System.getProperty("user.dir");
            System.setProperty("krystal.home", KRYSTAL_HOME);
        }
        tempFilePath = KRYSTAL_HOME + File.separator + "/webapps/DMC/images/unsupport.pdf";
        tempFile = new File(tempFilePath);
    }
    return tempFile;
}

From source file:com.quix.aia.cn.imo.mapper.ApplicationFormPDFMaintenance.java

License:Open Source License

public static InterviewCandidateMaterial pdf(HttpServletRequest request, AddressBook addressbook) {
    // TODO Auto-generated method stub
    log.log(Level.INFO, "ApplicationFormPDFMaintenance --> pdf ");
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    //Font myAdobeTypekit = FontFactory.getFont(request.getRealPath(File.separator)+"resources"+File.separator+"HDZB_35.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

    try {/*from   w w w .j a v  a 2s. c om*/
        //String fontPath = "C:/Windows/Fonts";

        String fontPath = request.getRealPath("/") + "resources" + File.separator + "hxb-meixinti";
        File f2 = new File(fontPath + "/hxb-meixinti.ttf");
        BaseFont bf1 = null;
        if (f2.exists()) {
            bf1 = BaseFont.createFont(fontPath + "/hxb-meixinti.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        } else {
            f2 = new File(fontPath + "/hxb-meixinti.ttf");

            if (f2.exists()) {
                System.out.println("File existed");
                bf1 = BaseFont.createFont(fontPath + "hxb-meixinti.ttf", BaseFont.IDENTITY_V,
                        BaseFont.EMBEDDED);
            } else {
                bf1 = BaseFont.createFont(FontManager.getFontPath(true) + "/hxb-meixinti.ttf",
                        BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }
        }

        Font normalFontCH = new Font(bf1, 15);

        String fileName = request.getRealPath("/") + "resources" + File.separator + "upload" + File.separator;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = new Date();
        String time = (d1.getTime() + "").trim();
        String str = df.format(new Date()) + time;

        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(fileName + "ApplicationForm_" + str + ".pdf"));
        InterviewCandidateMaterial material = new InterviewCandidateMaterial();
        material.setMaterialFileName("ApplicationForm_" + str + ".pdf");
        material.setCandidateCode(Integer.parseInt(request.getParameter("candidateCode")));
        material.setInterviewCode(Integer.parseInt(request.getParameter("interviewCode")));

        // PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://applicatonForm2.pdf"));
        document.open();

        addTitle(document, writer, "formHeaderTitle", "Application Form");
        document = personalInformation(document, writer, addressbook, normalFontCH);
        document = familyInformation(document, writer, addressbook);
        document = workExperience(document, writer, addressbook);
        document = Education(document, writer, addressbook);
        document = personalCertification(document, writer, addressbook);
        document = ESingnature(document, writer, addressbook);

        document.close();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        File file = new File(fileName + "ApplicationForm_" + str + ".pdf");
        FileInputStream fis = new FileInputStream(file);
        byte[] buf = new byte[1024];
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum); //no doubt here is 0
        }
        material.setFormContent(bos.toByteArray());
        material.setCreatedDate(new Date());
        material.setMaterialDescrption("AppicationForm");

        //  applicationForm.setFormContent(bos.toByteArray());

        return material;
    } catch (Exception e) {
        log.log(Level.INFO, "ApplicationFormPDFMaintenance --> pdf --> Exception  " + e.getMessage());
        e.printStackTrace();
        e.printStackTrace();
        LogsMaintenance logsMain = new LogsMaintenance();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logsMain.insertLogs("ApplicationFormPDFMaintenance", Level.SEVERE + "", errors.toString());
    }

    return null;

}

From source file:com.raghav.plot.ImageIntoPDF.java

public static void main(String[] args) throws Exception {
    Document document = new Document(PageSize.A4);

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/raghav/zzzzz.pdf"));
    document.open();//  www  .j  av  a  2s. c o m
    document.newPage();

    //for 4 photo
    //        for (int i=0;i<2;i++) {
    //            Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png");
    //            image1.setAbsolutePosition(40,80+(350*i));
    //          image1.scaleAbsolute(200, 260);
    //            document.add(image1);
    //        }
    //          for (int i=0;i<2;i++) {
    //            Image image1 = Image.getInstance("/home/raghav/Desktop/Firmway-Reco.png");
    //            image1.setAbsolutePosition(300, 80+(350*i));
    //          image1.scaleAbsolute(260, 200);
    //            document.add(image1);
    //        }
    //for 6

    float margin = 10;

    float docHeight = ((document.getPageSize().getHeight()) / 3) - (2 * margin);
    float docwidth = ((document.getPageSize().getWidth()) / 2) - (2 * margin);

    for (int i = 0; i < 3; i++) {
        Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg");

        image1.setAbsolutePosition(margin, margin * (i + 1) + (docHeight * i));
        image1.scaleToFit(docwidth, docHeight);
        //image1.scaleAbsolute(190, 130);
        document.add(image1);
    }
    for (int i = 0; i < 3; i++) {
        Image image1 = Image.getInstance("/home/raghav/myps/i1.jpeg");
        image1.setAbsolutePosition(docwidth + (2 * margin), margin * (i + 1) + (docHeight * i));
        image1.scaleToFit(docwidth, docHeight);
        document.add(image1);
    }
    document.close();
}

From source file:com.rapidminer.gui.actions.ExportPdfAction.java

License:Open Source License

/**
 * Create the PDF from a {@link Component}.
 * //from ww  w. j  a  v a  2  s . c  om
 * @param component
 */
private void createPdf(Component component) {
    if (component == null) {
        return;
    }

    // prompt user for pdf location
    File file = promptForPdfLocation();
    if (file == null) {
        return;
    }

    try {
        // create pdf document
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        createPdfViaTemplate(component, document, cb);
        document.close();
    } catch (Exception e) {
        SwingTools.showSimpleErrorMessage("cannot_export_pdf", e, e.getMessage());
    }
}

From source file:com.rapidminer.gui.actions.ExportPdfAction.java

License:Open Source License

/**
 * Create the PDF from a {@link PlotterTemplate}.
 * //from  w  w w .j  a va2s  . co m
 * @param template
 */
private void createPdf(PlotterTemplate template) {
    if (template == null) {
        return;
    }

    // prompt user for pdf location
    File file = promptForPdfLocation();
    if (file == null) {
        return;
    }

    try {
        // create pdf document
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        createPdfViaTemplate(template, document, cb);
        document.close();
    } catch (Exception e) {
        SwingTools.showSimpleErrorMessage("cannot_export_pdf", e, e.getMessage());
    }
}