Example usage for com.itextpdf.text.pdf PdfWriter getDirectContent

List of usage examples for com.itextpdf.text.pdf PdfWriter getDirectContent

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter getDirectContent.

Prototype


public PdfContentByte getDirectContent() 

Source Link

Document

Use this method to get the direct content for this document.

Usage

From source file:com.ephesoft.dcma.util.PDFUtil.java

License:Open Source License

/**
 * The <code>getSelectedPdfFile</code> method is used to limit the file
 * to the page limit given.// w  w w. j  ava 2 s .c o m
 * 
 * @param pdfFile {@link File} pdf file from which limit has to be applied
 * @param pageLimit int
 * @throws IOException if file is not found
 * @throws DocumentException if document cannot be created
 */
public static void getSelectedPdfFile(final File pdfFile, final int pageLimit)
        throws IOException, DocumentException {
    PdfReader reader = null;
    Document document = null;
    PdfContentByte contentByte = null;
    PdfWriter writer = null;
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    File newFile = null;
    if (null != pdfFile && pdfFile.exists()) {
        try {
            document = new Document();
            fileInputStream = new FileInputStream(pdfFile);

            String name = pdfFile.getName();
            final int indexOf = name.lastIndexOf(IUtilCommonConstants.DOT);
            name = name.substring(0, indexOf);
            final String finalPath = pdfFile.getParent() + File.separator + name + System.currentTimeMillis()
                    + IUtilCommonConstants.EXTENSION_PDF;
            newFile = new File(finalPath);
            fileOutputStream = new FileOutputStream(finalPath);
            writer = PdfWriter.getInstance(document, fileOutputStream);
            document.open();
            contentByte = writer.getDirectContent();

            reader = new PdfReader(fileInputStream);
            for (int i = 1; i <= pageLimit; i++) {
                document.newPage();

                // import the page from source pdf
                final PdfImportedPage page = writer.getImportedPage(reader, i);

                // add the page to the destination pdf
                contentByte.addTemplate(page, 0, 0);
                page.closePath();
            }
        } finally {
            closePassedStream(reader, document, contentByte, writer, fileInputStream, fileOutputStream);
        }
        if (pdfFile.delete() && null != newFile) {
            newFile.renameTo(pdfFile);
        } else {
            if (null != newFile) {
                newFile.delete();
            }
        }
    }
}

From source file:com.example.admin.avoidq.billGenerated.java

private void generatePDF(final String personName) {
    new Thread(new Runnable() {
        public void run() {
            // a potentially  time consuming task

            //create a new document
            Document document = new Document();

            try {

                PdfWriter docWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
                document.open();/*from  w  w  w.  ja  v a 2  s  .c om*/

                PdfContentByte cb = docWriter.getDirectContent();
                //initialize fonts for text printing
                initializeFonts();

                //the company logo is stored in the assets which is read only
                //get the logo and print on the document
                /*
                try {
                        
                bitmap11 = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
                iv.setImageBitmap(bitmap11);
                        
                } catch (WriterException e) {
                e.printStackTrace();
                }
                * */
                InputStream inputStream = getAssets().open("sale.png");

                Bitmap bmp = null;//BitmapFactory.decodeStream(inputStream);
                bmp = bitmap11;
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

                Image companyLogo = Image.getInstance(stream.toByteArray());
                companyLogo.setAbsolutePosition(25, 700);
                companyLogo.scalePercent(65);
                document.add(companyLogo);
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
                String formattedDate = df1.format(calendar.getTime());

                //creating a sample invoice with some customer data
                createHeadings(cb, 400, 780, "Date :");
                createHeadings(cb, 430, 780, formattedDate);

                String fname = customer.getName();
                String lname = customer.getSurname();
                createHeadings(cb, 400, 765, "Customer :");
                createHeadings(cb, 445, 765, fname + " " + lname);

                String mob = customer.getMobile_no();
                createHeadings(cb, 400, 750, "Mobile No :");
                createHeadings(cb, 445, 750, mob);

                createHeadings(cb, 400, 735, "Shop :");
                createHeadings(cb, 430, 735, "Empress Mall");

                createHeadings(cb, 400, 720, "City :");
                createHeadings(cb, 430, 720, "Nagpur");
                // createHeadings(cb,400,720,"Country");

                //list all the products sold to the customer
                float[] columnWidths = { 1.5f, 3f, 2.5f, 2.5f, 2f, 2f };
                //create PDF table with the given widths
                PdfPTable table = new PdfPTable(columnWidths);
                // set table width a percentage of the page width
                table.setTotalWidth(500f);

                PdfPCell cell = new PdfPCell(new Phrase("S.NO"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Item Name"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Price"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Quantity"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Discount"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("Amount"));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                table.setHeaderRows(1);

                /*DecimalFormat df = new DecimalFormat("0.000");
                for(int i=0; i < 10; i++ ){
                    double price = Double.valueOf(df.format(Math.random() * 10));
                    double extPrice = price * (i+1) ;
                    table.addCell(String.valueOf(i+1));
                    table.addCell("ITEM" + String.valueOf(i+1));
                    table.addCell(String.valueOf(5*i));
                    table.addCell(String.valueOf(1));
                    table.addCell(String.valueOf(i)+ " %");
                    table.addCell(df.format(extPrice));
                }*/
                int sr = 0;
                DecimalFormat df = new DecimalFormat("0.0");
                double total_price = 0;
                //Log.i("c0","c0 = "+carts[0].getItemname()+" "+String.valueOf(carts[0].getPrice()));
                // Log.i("c1","c1 = "+carts[1].getItemname()+" "+String.valueOf(carts[1].getPrice()));
                for (Cart cd : carts) {
                    Log.i("cartscheck", "carts check = " + cd.getBarcode() + " " + cd.getItemname() + " "
                            + String.valueOf(cd.getPrice()));
                }
                for (Cart c : carts) {
                    double price = c.getPrice();
                    int quantity = c.getQuantity();
                    price = (price / quantity);
                    double discont = c.getDiscount();
                    sr++;
                    table.addCell(String.valueOf(sr));
                    table.addCell(c.getItemname());
                    table.addCell(df.format(price));
                    table.addCell(String.valueOf(quantity));
                    table.addCell(df.format(discont) + " %");

                    double total = (price * quantity);
                    total_price = total_price + total;
                    Log.i("total", "total in for loop = " + String.valueOf(total));
                    table.addCell(df.format(total));

                }
                float headerHeight = table.getHeaderHeight();
                Log.i("headerHeight", String.valueOf(headerHeight));
                //absolute location to print the PDF table from
                table.writeSelectedRows(0, -1, document.leftMargin(), 650, docWriter.getDirectContent());
                float total_height = table.getTotalHeight();
                Log.i("total_height", String.valueOf(total_height));
                createHeadings(cb, 420, 750f - 125f - total_height, "Total Price = ");
                createHeadings(cb, 475, 750f - 125f - total_height, String.valueOf(total_price));

                //print the signature image along with the persons name
                inputStream = getAssets().open("user.png");
                bmp = BitmapFactory.decodeStream(inputStream);
                stream = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                Image signature = Image.getInstance(stream.toByteArray());
                signature.setAbsolutePosition(400f, 750f - 125f - total_height - 60f);
                signature.scalePercent(35f);
                document.add(signature);

                createHeadings(cb, 450, 750f - 125f - total_height - 80f, fname + " " + lname);

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

            //PDF file is now ready to be sent to the bluetooth printer using PrintShare
            Intent i = new Intent(Intent.ACTION_VIEW);
            //   i.setPackage("com.dynamixsoftware.printershare");
            i.setDataAndType(Uri.fromFile(pdfFile), "application/pdf");
            startActivity(i);

        }
    }).start();

}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

private void writePageNumber(final PdfWriter writer) throws Exception {
    if (isPrintPageNumbers()) {
        writePageNumber(writer.getDirectContent());
    }// w ww .j a  v a  2s .co m
}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

private void addPdf(final File file, final Document document, final PdfWriter writer) throws Exception {
    PdfReader pdfReader = null;/*from  www .  j av  a2s .com*/
    try (InputStream is = new FileInputStream(file)) {
        pdfReader = new PdfReader(is);
        PdfContentByte cb = writer.getDirectContent();
        for (int currentPage = 1; currentPage <= pdfReader.getNumberOfPages(); currentPage++) {
            Rectangle currentPageSize = pdfReader.getPageSize(currentPage);
            document.setPageSize(currentPageSize);
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(pdfReader, currentPage);
            cb.addTemplate(page, 0, 0);
            writePageNumber(cb);

        }
        writer.flush();
    } finally {
        if (pdfReader != null) {
            writer.freeReader(pdfReader);
            ItextUtils.close(pdfReader);
        }
    }
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void CreateTablePDF(JTable tabla) {
    boolean shapes = false;
    Document document = new Document();
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));
    File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
    if (!Dir.exists()) {
        Dir.mkdirs();//from   www . j av a 2 s.c  o m
    }
    try {
        PdfWriter writer;
        if (shapes) {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        } else {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(500, 500);
        Graphics2D g2;
        if (shapes) {
            g2 = tp.createGraphicsShapes(500, 500);
        } else {
            g2 = tp.createGraphics(500, 500);
        }

        g2.dispose();
        cb.addTemplate(tp, 30, 300);
    } catch (Exception e) {
        Log.SaveLog(e.toString());
    }
    document.close();
}

From source file:com.github.ossdevs.jhocr.converter.HocrPageProcessor.java

License:Open Source License

/**
 * This method will process the {@link com.itextpdf.text.Document} fitting the image into the documents page.
 *
 * @param document  will be processed./*from   ww w.  j av  a2s . c om*/
 * @param pdfWriter will be used to process the {@link com.itextpdf.text.Document}
 */
public boolean process(Document document, PdfWriter pdfWriter) {
    try {

        if (initialized) {
            document.setPageSize(getImageRectangle());

            if (!document.isOpen()) {
                document.open();
            } else {
                document.newPage();
            }

            PdfContentByte cb = pdfWriter.getDirectContentUnder();

            /**
             * This will fit the image into the documents page using the width and height from the image and fitting it into x0 and y0 of the page.
             */
            getImage().scaleToFit(getImageRectangle().getWidth(), getImageRectangle().getHeight());
            getImage().setAbsolutePosition(0, 0);

            pdfWriter.getDirectContent().addImage(getImage());

            for (HocrLine hocrLine : getHocrPage().getLines()) {
                processHocrLine(cb, hocrLine);
            }
        }

        return true;

    } catch (DocumentException e) {
        logger.error("Document could not be processed.", e);
        return false;
    }
}

From source file:com.github.ukase.bulk.BulkRenderTask.java

License:Open Source License

private void mergeSubTasksPdfs() {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();//from  ww w  .  j a  v a 2s .co  m
        PdfContentByte cb = writer.getDirectContent();

        appendPdfs(document, writer, cb);

        document.close();
        pdf = baos.toByteArray();
    } catch (IOException | DocumentException e) {
        log.warn("Cannot bulk pdfs", e);
    } finally {
        registerResult();
    }
}

From source file:com.github.wolfposd.imsqti2pdf.HeaderFooter.java

License:Open Source License

private void pageNumberFooter(PdfWriter writer, Rectangle rect) {
    Chunk c = new Chunk(
            String.format(LocaleStrings.getString("page"), writer.getPageNumber(), _maximumPageNumber));
    c.setFont(new Font(FontFamily.HELVETICA, 10));
    Phrase pagephrase = new Phrase(c);

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, pagephrase,
            rect.getRight() - 60, rect.getBottom() - 30, 0);
}

From source file:com.github.wolfposd.imsqti2pdf.HeaderFooter.java

License:Open Source License

private void sumSymboltoFooter(PdfWriter writer, Rectangle rect) {
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, _sumSymbol, rect.getLeft() - 10,
            rect.getBottom() - 30, 0);//from www. java 2 s.c om
}

From source file:com.github.wolfposd.imsqti2pdf.HeaderFooter.java

License:Open Source License

@SuppressWarnings("unused")
private void headerText(PdfWriter writer, Rectangle rect) {
    float center = (rect.getLeft() + rect.getRight()) / 2;

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Header Text"),
            center, rect.getTop(), 0);//from   w w  w .ja  v a2 s.  c o m

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("01.01.1970"),
            center, rect.getTop() - 16, 0);
}