Example usage for com.itextpdf.text Document Document

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

Introduction

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

Prototype


public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom) 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:com.mim.controllers.HomeCtrl.java

public String buildReport() {

    System.out.println("orden No. " + ordenId);

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    //response.setContentType("application/pdf");
    //response.setHeader("Content-disposition", "inline=filename=file.pdf");

    // Get the text that will be added to the PDF
    current = ordenFacade.find(Integer.parseInt(ordenId));
    System.out.println("equipo: " + current.getEquipoIdequipo().getLugarIdlugar().getNombre());
    // step 1/*from   w  w w.  jav  a 2  s  .  c o  m*/
    Document document = new Document(new Rectangle(800, 700), 7f, 7f, 50f, 7f);

    if (ordenId.equals("n/a")) {
        current.setNumeroOrden(current.getActividad());
    }

    equipo = current.getEquipoIdequipo();
    Lugar lugar = equipo.getLugarIdlugar();

    //PdfWriter.getInstance(document, new FileOutputStream(orden.getNumeroOrden() + ".pdf"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        PdfWriter.getInstance(document, baos);

        document.open();
        ordenReport(document, lugar);
        //document.add(new Paragraph("dsadasdas"));
        document.close();

        // step 2
        // setting some response headers
        response.setHeader("Content-disposition", "attachment; filename=" + current.getNumeroOrden() + ".pdf");// esto hizo que fuera descarga directa
        //response.setHeader("Expires", "0");
        //response.setHeader("Cache-Control",
        //        "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());
        try ( // write ByteArrayOutputStream to the ServletOutputStream
                OutputStream os = response.getOutputStream()) {
            baos.writeTo(os);
            os.flush();
        }
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(HomeCtrl.class.getName()).log(Level.SEVERE, null, ex);
    }

    context.responseComplete();
    return null;

}

From source file:com.mim.controllers.OrdenCtrl.java

public String buildReport() {

    System.out.println("orden No. " + ordenId);

    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    //response.setContentType("application/pdf");
    //response.setHeader("Content-disposition", "inline=filename=file.pdf");

    // Get the text that will be added to the PDF
    current = ordenFacade.find(Integer.parseInt(ordenId));
    System.out.println("lugar equipo: " + current.getEquipoIdequipo().getLugarIdlugar().getNombre());
    // step 1//from   ww w .j  a  v  a  2  s. c o m
    Document document = new Document(new Rectangle(800, 700), 7f, 7f, 50f, 7f);

    if (ordenId.equals("n/a")) {
        current.setNumeroOrden(current.getActividad());
    }

    equipo = current.getEquipoIdequipo();
    Lugar lugar = equipo.getLugarIdlugar();

    //PdfWriter.getInstance(document, new FileOutputStream(orden.getNumeroOrden() + ".pdf"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        PdfWriter.getInstance(document, baos);

        document.open();
        ordenReport(document, lugar);
        //document.add(new Paragraph("dsadasdas"));
        document.close();

        // step 2
        // setting some response headers
        response.setHeader("Content-disposition", "attachment; filename=" + current.getNumeroOrden() + ".pdf");// esto hizo que fuera descarga directa
        //response.setHeader("Expires", "0");
        //response.setHeader("Cache-Control",
        //        "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());
        try ( // write ByteArrayOutputStream to the ServletOutputStream
                OutputStream os = response.getOutputStream()) {
            baos.writeTo(os);
            os.flush();
        }
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(HomeCtrl.class.getName()).log(Level.SEVERE, null, ex);
    }

    context.responseComplete();
    return null;

}

From source file:com.mim.servlet.ReportGen.java

public String buildReport(HttpServletResponse response) {

    System.out.println("orden No. " + ordenId);

    FacesContext context = FacesContext.getCurrentInstance();

    //response.setContentType("application/pdf");
    //response.setHeader("Content-disposition", "inline=filename=file.pdf");

    // Get the text that will be added to the PDF
    current = ordenFacade.find(Integer.parseInt(ordenId));
    System.out.println("equipo: " + current.getEquipoIdequipo().getLugarIdlugar().getNombre());
    // step 1//from   w  w w  .j a  v  a2  s. co m
    Document document = new Document(new Rectangle(800, 700), 7f, 7f, 50f, 7f);

    if (ordenId.equals("n/a")) {
        current.setNumeroOrden(current.getActividad());
    }

    equipo = current.getEquipoIdequipo();
    Lugar lugar = equipo.getLugarIdlugar();

    //PdfWriter.getInstance(document, new FileOutputStream(orden.getNumeroOrden() + ".pdf"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        PdfWriter.getInstance(document, baos);

        document.open();
        ordenReport(document, lugar);
        //document.add(new Paragraph("dsadasdas"));
        document.close();

        // step 2
        // setting some response headers
        response.setHeader("Content-disposition", "attachment; filename=" + current.getNumeroOrden() + ".pdf");// esto hizo que fuera descarga directa
        //response.setHeader("Expires", "0");
        //response.setHeader("Cache-Control",
        //        "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());
        try ( // write ByteArrayOutputStream to the ServletOutputStream
                OutputStream os = response.getOutputStream()) {
            baos.writeTo(os);
            os.flush();
        }
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(HomeCtrl.class.getName()).log(Level.SEVERE, null, ex);
    }

    context.responseComplete();
    return null;

}

From source file:com.mx.ipn.clases.PDF.java

public void crearpdf(String nombre, String appat, String apmat)
        throws FileNotFoundException, DocumentException {
    // Creacion del documento con los margenes
    // Creacion del documento con los margenes
    Document document = new Document(PageSize.A4, 35, 30, 50, 50);
    try {//from w ww .ja v a2 s . com

        // El archivo pdf que vamos a generar
        FileOutputStream fileOutputStream = new FileOutputStream("AvisoPrivacidad.pdf");

        // Obtener la instancia del PdfWriter
        PdfWriter.getInstance(document, fileOutputStream);

        // Abrir el documento
        document.open();

        // Crear las fuentes para el contenido y los titulos
        Font fontContenido = FontFactory.getFont(FontFactory.TIMES_ROMAN.toString(), 9, Font.NORMAL,
                BaseColor.DARK_GRAY);
        Font fontTitulos = FontFactory.getFont(FontFactory.TIMES_BOLD, 11, Font.UNDERLINE, BaseColor.DARK_GRAY);
        Font nomb = FontFactory.getFont(FontFactory.TIMES_BOLD, 9, Font.NORMAL, BaseColor.DARK_GRAY);

        // Creacion del parrafo
        Paragraph paragraph = new Paragraph();

        // Agregar un titulo con su respectiva fuente
        paragraph.add(new Phrase("Aviso de Privacidad", fontTitulos));
        paragraph.setAlignment(Element.ALIGN_CENTER);

        // Agregar saltos de linea
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));

        // Agregar contenido con su respectiva fuente
        paragraph.add(new Phrase(
                "Con fundamento en los artculos 15, 16 y de acuerdo a lo Previsto en la Ley Federal de Proteccin de Datos"
                        + "Personales, hacemos de su conocimiento que ZERCHERS, S.A. de C.V., es una empresa legalmente"
                        + "constituido de conformidad con las leyes mexicanas, con domicilio en Av. Juan de Dios Btiz s/n, Gustavo"
                        + "A. Madero, Nueva Industrial Vallejo, 07700 Ciudad de Mxico; y como responsable del tratamiento de sus"
                        + "datos personales, del uso que se le d a los mismos y de su proteccin. Hace de su conocimiento que la"
                        + "informacin de nuestros clientes es tratada de forma estrictamente confidencial por lo que, al proporcionar"
                        + "sus datos personales. Estos sern utilizados nica y exclusivamente para los siguientes fines: "
                        + "Proveer los servicios y productos que ha solicitado; notificarle sobre nuevos servicios o productos que"
                        + "tengan relacin con los ya contratados o adquiridos; comunicarle sobre cambios en los mismos; evaluar la"
                        + "calidad de los servicios que brindamos; mantener actualizada nuestra base de datos con sus datos"
                        + "recientes y en general, para dar cumplimiento a las obligaciones que hemos contrado con usted.",
                fontContenido));

        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(
                " Para las finalidades antes mencionadas, requerimos obtener los siguientes datos personales:",
                fontContenido));
        paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        // Agregar el parrafo al documento
        document.add(paragraph);

        document.add(Tabla_Simple());
        paragraph = new Paragraph();
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));

        paragraph.add(new Phrase(
                "Para prevenir el acceso no autorizado a sus datos personales y con el fin de asegurar que la informacin sea "
                        + "utilizada para los fines establecidos en este aviso de privacidad, hemos establecido diversos procedimientos"
                        + " con la finalidad de evitar el uso o divulgacin no autorizados de sus datos, permitindonos tratarlos debidamente."
                        + "  As mismo, le informamos que sus datos personales pueden ser Transmitidos para ser tratados por personas "
                        + "distintas a esta empresa.   Todos sus datos personales son tratados de acuerdo a la legislacin aplicable y "
                        + "vigente en el pas, por ello le informamos que usted tiene en todo momento los derechos (ARCO) de acceder, "
                        + "rectificar, cancelar u oponerse al tratamiento que le damos a sus datos personales; derecho que podr "
                        + "hacer valer a travs del ?rea de Privacidad encargada de la seguridad de datos personales en el "
                        + "Telfono 5729 6000.",
                fontContenido));
        paragraph.setAlignment(Element.ALIGN_JUSTIFIED);

        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));

        paragraph.add(new Phrase(
                " A travs de estos canales usted podr actualizar sus datos y especificar el medio por el cual desea recibir "
                        + "informacin, ya que en caso de no contar con esta especificacin de su parte, ZERCHERS, S.A. de C.V., "
                        + "establecer libremente el canal que considere pertinente para enviarle informacin.  Este aviso de"
                        + " privacidad podr ser modificado por ZERCHERS, S.A. de C.V., dichas modificaciones sern oportunamente "
                        + "informadas a travs de correo electrnico, telfono, pgina web o cualquier otro medio de comunicacin"
                        + " que ZERCHERS, S.A. de C.V., determine para tal efecto.",
                fontContenido));
        paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));

        paragraph.add(new Phrase(" ATENTAMENTE", nomb));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(" Direccin General TT/SisPLD", nomb));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(" Consiento que mis datos personales sensibles sean tratados conforme a"
                + "los trminos y condiciones del presente aviso de privacidad.", fontContenido));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase("Nombre: " + nombre + " " + appat + " " + apmat, nomb));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase("____________________________________", fontContenido));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(Chunk.NEWLINE));
        paragraph.add(new Phrase(" ltima Fecha de Emisin:  Mayo 13, 2016", fontContenido));

        document.add(paragraph);

        // Cerrar el documento
        document.close();

        // Abrir el archivo
        File file = new File("AvisoPrivacidad.pdf");
        Desktop.getDesktop().open(file);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.mycompany.peram_inclassexam.WritePDFFile.java

public void createPDF(AccountDetails account)
        throws DocumentException, FileNotFoundException, BadElementException, IOException {

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    PdfWriter write = PdfWriter.getInstance(document,
            new FileOutputStream(account.getLastName() + "_output.pdf"));

    document.open();//from   ww  w  .j a  v  a2 s.c om

    Image image = Image.getInstance("image.png");

    image.scaleToFit(450f, 1800f);

    document.add(image);
    document.add(new Paragraph(
            "--------------------------------------------------------------------------------------------------------------------------"));

    Paragraph welcomeParagraph = new Paragraph(
            "Welcome! " + account.getFirstName() + " " + account.getLastName() + "!");
    welcomeParagraph.setSpacingBefore(50);

    document.add(welcomeParagraph);

    String firstName = "First Name: " + account.getFirstName();
    String lastName = "Last Name: " + account.getLastName();
    String acctNumber = "Account Number: " + account.getAccountNo();
    String acctBalance = String.format("Account Balance: $%.1f", account.getAccountBalance());

    Paragraph detailsPara = new Paragraph("Below are your Account Details:\n" + firstName + "\n" + lastName
            + "\n" + acctNumber + "\n" + acctBalance);
    detailsPara.setIndentationLeft(30);
    detailsPara.setSpacingBefore(20);
    document.add(detailsPara);

    document.close();
    write.close();
}

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.  jav  a  2s .  c om
    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.j  a v a2 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.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();// www.  ja v  a 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.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.ostrichemulators.semtool.util.ExportUtility.java

License:Open Source License

public static void exportAsPdf(BufferedImage img, File pdf) throws IOException, DocumentException {
    final double MAX_DIM = 14400;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "PNG", baos);
    Image image1 = Image.getInstance(baos.toByteArray(), true);
    Rectangle r;/*from w w  w  . j a  va2  s  .  co  m*/
    if (image1.getHeight() > MAX_DIM) {
        r = new Rectangle((int) image1.getWidth(), (int) MAX_DIM);
    } else if (image1.getWidth() > MAX_DIM) {
        r = new Rectangle((int) MAX_DIM, (int) image1.getHeight());
    } else {
        r = new Rectangle((int) image1.getWidth() + 20, (int) image1.getHeight() + 20);
    }
    Document document = new Document(r, 15, 25, 15, 25);
    PdfWriter.getInstance(document, new FileOutputStream(pdf));
    document.open();

    int pages = (int) Math.ceil((double) img.getHeight() / MAX_DIM);
    if (pages == 0) {
        pages = 1;
    }
    for (int i = 0; i < pages; i++) {
        BufferedImage temp;
        if (i < pages - 1) {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), (int) MAX_DIM);
        } else {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), img.getHeight() % (int) MAX_DIM);
        }
        File tempFile = new File(i + Constants.PNG);
        ImageIO.write(temp, Constants.PNG, tempFile);
        Image croppedImage = Image.getInstance(i + Constants.PNG);
        document.add(croppedImage);
        tempFile.delete();
        if (i < pages - 1) {
            document.newPage();
        }
    }

    document.close();
}

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);
        }//  w w  w.  j  a  v a  2 s  .com
    } 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());
    }
}