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:Controller.PrintOrderManagedBean.java

public void executePDF(String maDH) {
    try {// w  w  w. ja va2 s .  c  o  m

        DonHang donhang = new DonHang();
        donhang.init(maDH);
        float CONVERT = 28.346457f;// 1 cm
        FacesContext faces = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Content-disposition","inline; filename=kiran.pdf");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        //response.setHeader("Content-Disposition", "attachment;filename=\"ContactList.pdf\"");
        response.addHeader("Content-disposition", "attachment;filename=\"DataListBean.pdf\"");
        //step 1: creation of a document-object
        Document document = new Document(PageSize.A4, 0.5f * CONVERT, 0.5f * CONVERT, 1.0f * CONVERT,
                1.0f * CONVERT);
        //step 2: we create a writer that listens to the document
        // and directs a PDF-stream to a temporary buffer
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);
        Font font = new Font(bf, 18, Font.BOLD);
        Font font11 = new Font(bf, 11, Font.NORMAL);
        Font font11_bo = new Font(bf, 11, Font.BOLD);
        Font font12 = new Font(bf, 12, Font.NORMAL);
        Font font10 = new Font(bf, 10, Font.NORMAL);
        Font font9 = new Font(bf, 9, Font.NORMAL);
        //step 3: we open the document
        document.open();

        PdfPTable tab_Header1;
        tab_Header1 = new PdfPTable(1);
        tab_Header1.setWidthPercentage(100);

        tab_Header1.setHorizontalAlignment(Element.ALIGN_CENTER);

        PdfPCell cell1;
        cell1 = new PdfPCell(new Phrase("CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S?T: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?N GIAO HNG", font12));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Bn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Mua:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: " + donhang.getTenKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch: " + donhang.getDiaChiKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: " + donhang.getSoDTKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Vn chuyn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn:....................................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Danh sch hng ha:", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);
        ///////////////////////////////bn sn phm
        float[] crDonHang = { 1.0f * CONVERT, 4.0f * CONVERT, 1.0f * CONVERT, 2.0f * CONVERT, 2.0f * CONVERT };

        PdfPTable tab_Header2;
        tab_Header2 = new PdfPTable(crDonHang.length);
        tab_Header2.setWidthPercentage(100);
        tab_Header2.setWidths(crDonHang);
        tab_Header2.setHorizontalAlignment(Element.ALIGN_CENTER);
        NumberFormat formatter = new DecimalFormat("#,###,###");

        String[] crheader = { "STT", "Tn Hng", "S Lng", "Gi Bn(VN?)", "Thnh Ti?n(VN?)" };

        for (int i = 0; i < crheader.length; i++) {
            PdfPCell cell = new PdfPCell(new Phrase(crheader[i], font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);
        }
        int stt = 1;
        for (SanPhamDH sp : donhang.getListSP()) {

            PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(stt), font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getTenSP(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getSoluong(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getGiaSP())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getThanhTien())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            stt++;
        }
        cell1 = new PdfPCell(tab_Header2);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n hng:   "
                + formatter.format(
                        Double.parseDouble(donhang.getTienTamTinh() == null ? "0" : donhang.getTienTamTinh()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n vn chuyn:   "
                + formatter.format(Double
                        .parseDouble(donhang.getTienVanChuyen() == null ? "0" : donhang.getTienVanChuyen()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n thanh ton:   "
                + formatter.format(Double.parseDouble(donhang.getTongTien())) + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S ti?n thanh ton bng ch: "
                + DocTien.doctien(donhang.getTongTien().replaceAll(" ", "")) + "ng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("TP H Ch Minh, ngy      thng       nm       ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingRight(1.0f * CONVERT);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        PdfPTable tab_Header3;
        tab_Header3 = new PdfPTable(3);
        tab_Header3.setWidthPercentage(100);

        tab_Header3.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell1 = new PdfPCell(new Phrase("Ng?i nhn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i giao hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i bn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(tab_Header3);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        document.add(tab_Header1);

        document.close();
        //step 6: we output the writer as bytes to the response output
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        baos.flush();
        faces.responseComplete();

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

From source file:cv.mikusher.outros.exemploescola.PrimeiroPDF.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Document doc = null;/* ww  w .ja  v  a  2s . co m*/
    OutputStream os = null;

    try {
        doc = new Document(PageSize.A4, 72, 72, 72, 72);

        os = new FileOutputStream("C://outPdf.pdf");

        PdfWriter.getInstance(doc, os);

        doc.open();
        Font ftT = new Font(Font.FontFamily.COURIER, 20, Font.BOLD);

        Paragraph pr_1 = new Paragraph("Meu primeiro arquivo PDF.", ftT);
        doc.add(pr_1);

        Paragraph pr_2 = new Paragraph("Ola mundo, um documento PDF criado em JAVA");
        doc.add(pr_2);

        //Image img = Image.getInstance("mikusher.jpg");
        //img.setAlignment(Element.ALIGN_CENTER);
        //doc.add(img);

    } finally {
        if (doc != null) {
            doc.close();
        }
        if (os != null) {
            os.close();
        }
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.pdf.PDFUtils.java

License:Apache License

public Paragraph setHeader(Document document, String title) throws IOException, BadElementException {
    Paragraph paragraph = new Paragraph(title,
            FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, BaseColor.BLACK));
    paragraph.setAlignment(Element.ALIGN_CENTER);

    Image img = GetResizedAndCenteredImage(path + convertPath("/files/images/" + HEADERIMG));
    float topMargin = img.getHeight() + 2 * PADDING[0];
    img.setAbsolutePosition(PADDING[3], (PageSize.A4.getHeight() - img.getHeight()) - PADDING[0]);
    paragraph.add(img);/*w w  w  .  j av a 2s. c  o m*/
    img = GetResizedAndCenteredImage(path + convertPath("/files/images/" + FOOTERIMG));
    img.setAbsolutePosition((PageSize.A4.getWidth() - img.getWidth()) / 2, PADDING[2]);
    paragraph.add(img);
    float bottomMargin = img.getHeight() + 2 * PADDING[2];

    document.setMargins(topMargin, PADDING[1], bottomMargin, PADDING[3]);

    paragraph.setSpacingAfter(1.5f * PADDING[0]);

    return paragraph;
}

From source file:cz.zcu.kiv.eegdatabase.logic.pdf.PDFUtils.java

License:Apache License

private Image GetResizedAndCenteredImage(String filename) throws IOException, BadElementException {
    Image img = Image.getInstance(filename);

    if (img.getWidth() <= PageSize.A4.getWidth() - PADDING[1] - PADDING[3]) {
        return img;
    }/*from  ww  w.  j  a  va  2s  .  com*/

    float newWidth = PageSize.A4.getWidth() - PADDING[1] - PADDING[3];
    float ratio = newWidth / img.getWidth();
    float newHeight = img.getHeight() * ratio;
    img.scaleAbsolute(newWidth, newHeight);

    return img;
}

From source file:cz.zcu.kiv.eegdatabase.logic.pdf.ReservationPDF.java

License:Apache License

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {/*  ww  w .java  2 s.c o m*/
        if (request.getParameter("type").compareTo("single") == 0) {
            int id = Integer.parseInt(request.getParameter("reservationId"));
            Reservation reservation = reservationDao.getReservationById(id);

            response.setHeader("Content-Type", "application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=reservation-" + id + ".pdf");

            Document document = new Document(PageSize.A4, 50, 50, 50, 50);
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/"));
            document.add(utils.setHeader(document, "Reservation listing"));

            /*Paragraph paragraph = new Paragraph("Reservation #" + id, FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, BaseColor.BLACK));
            paragraph.setAlignment(Element.ALIGN_CENTER);
            paragraph.setSpacingBefore(10);
            paragraph.setSpacingAfter(10);
            document.add(paragraph);*/

            document.add(formatReservation(reservation));

            document.close();
            response.flushBuffer();

            return null;
        }

        if (request.getParameter("type").compareTo("range") == 0) {

            String date = request.getParameter("date") + " 00:00:00";
            GregorianCalendar rangeStart = BookingRoomUtils.getCalendar(date);
            int length = Integer.parseInt(request.getParameter("length"));

            GregorianCalendar rangeEnd = (GregorianCalendar) rangeStart.clone();
            rangeEnd.add(Calendar.DAY_OF_YEAR, length);

            response.setHeader("Content-Type", "application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=reservations.pdf");

            Document document = new Document(PageSize.A4, 50, 50, 50, 50);
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/"));
            document.add(utils.setHeader(document, "Reservations listing"));

            java.util.List<Reservation> reservations = reservationDao.getReservationsBetween(rangeStart,
                    rangeEnd, "", 0);

            int count = 0;
            for (Reservation reservation : reservations) {
                document.add(formatReservation(reservation));
                if (++count % 6 == 0) {
                    document.newPage();
                    document.add(utils.setHeader(document, "Reservations listing"));
                }
            }
            document.close();
            response.flushBuffer();

            return null;
        }

        return null;
    } catch (Exception e) {
        ModelAndView mav = new ModelAndView(getFormView());
        Map data = new HashMap<String, Object>();
        data.put("error", e.getMessage());
        mav.addAllObjects(data);
        return mav;
    }
}

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

@Override
protected void performThreaded(ActionEvent e) throws Exception {
    boolean selection = false;
    JTable table = ResultSetTable.getInstance();
    if (table.getSelectedRowCount() > 0 && table.getSelectedRowCount() != table.getRowCount()) {
        Object option = Dialog.show("PDF", "Export", Dialog.QUESTION_MESSAGE,
                new Object[] { "Everything", "Selection" }, "Everything");
        if (option == null || "-1".equals(option.toString())) {
            return;
        }/*ww w  .java2 s  . c  o m*/
        selection = "Selection".equals(option);
    }
    List list = ((DefaultTableModel) table.getModel()).getDataVector();
    int columnCount = table.getColumnCount();
    PdfPTable pdfPTable = new PdfPTable(columnCount);
    pdfPTable.setWidthPercentage(100);
    pdfPTable.getDefaultCell().setPaddingBottom(4);
    int[] widths = new int[columnCount];

    // Row Header
    pdfPTable.getDefaultCell().setBorderWidth(2);
    for (int i = 0; i < columnCount; i++) {
        String columnName = table.getColumnName(i);
        pdfPTable.addCell(new Phrase(columnName, ROW_HEADER_FONT));
        widths[i] = Math.min(50000, Math.max(widths[i], ROW_HEADER_BASE_FONT.getWidth(columnName + " ")));
    }
    pdfPTable.getDefaultCell().setBorderWidth(1);
    if (!list.isEmpty()) {
        pdfPTable.setHeaderRows(1);
    }

    // Body
    for (int i = 0; i < list.size(); i++) {
        if (!selection || table.isRowSelected(i)) {
            List record = (List) list.get(i);
            for (int j = 0; j < record.size(); j++) {
                Object o = record.get(j);
                if (o != null) {
                    if (ResultSetTable.isLob(j)) {
                        o = Context.getInstance().getColumnTypeNames()[j];
                    }
                } else {
                    o = "";
                }
                PdfPCell cell = new PdfPCell(new Phrase(o.toString()));
                cell.setPaddingBottom(4);
                if (o instanceof Number) {
                    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                }
                pdfPTable.addCell(cell);
                widths[j] = Math.min(50000, Math.max(widths[j], BASE_FONT.getWidth(o.toString())));
            }
        }
    }

    // Size
    pdfPTable.setWidths(widths);
    int totalWidth = 0;
    for (int width : widths) {
        totalWidth += width;
    }
    Rectangle pageSize = PageSize.A4.rotate();
    pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
    pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));

    // Document
    Document document = new Document(pageSize);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();
    pdfTemplate = writer.getDirectContent().createTemplate(100, 100);
    pdfTemplate.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    writer.setPageEvent(this);
    document.add(pdfPTable);
    document.close();
    FileIO.saveAndOpenFile("export.pdf", byteArrayOutputStream.toByteArray());
}

From source file:de.aidger.utils.pdf.BalanceReportConverter.java

License:Open Source License

/**
 * Initializes this BalanceReportConverter with a given path and a name.
 * /*from w  w w .  j  a  v  a 2 s. c  o m*/
 * @param file
 *            The file of this report.
 * @param index
 *            What kind of report this is.
 * @param semester
 *            The semester of the report.
 * @param filters
 *            The filters for the report.
 * @param calculationMethod
 *            The calculation method of this report.
 */
@SuppressWarnings("unchecked")
public BalanceReportConverter(File file, int index, Object semester, BalanceFilter filters,
        int calculationMethod) {
    document = new Document(PageSize.A4.rotate());
    document.setMargins(document.leftMargin(), document.rightMargin(), document.topMargin() + 25,
            document.bottomMargin());
    this.filters = filters;
    balanceHelper = new BalanceHelper();
    this.calculationMethod = calculationMethod;
    file = checkExtension(file);
    switch (index) {
    case 1:
        name = _("Full balance report");
        break;
    case 2:
        name = _("Annual balance report") + " - " + semester;
        break;
    case 3:
        name = _("Semester balance report") + " - " + semester;
        break;
    }
    File preTemplateFile = null;
    try {
        preTemplateFile = File.createTempFile("BalanceReport", ".pdf");
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    makeNewDocument(preTemplateFile);
    if (fileCreated) {
        switch (index) {
        case 1:
            ArrayList semesters = new BalanceHelper().getSemesters();
            for (int i = 0; i < semesters.size(); i++) {
                if (new BalanceHelper().courseExists((String) semesters.get(i), filters)) {
                    createSemester((String) semesters.get(i));
                }
            }
            break;
        case 2:
            createYear((Integer) semester);
            break;
        case 3:
            createSemester((String) semester);
            break;
        }
        document.close();
        if (applyTemplate(file, preTemplateFile)) {
            preTemplateFile.delete();
            /*
             * Open the created document if the setting is enabled with the
             * specified pdf viewer.
             */
            if (Runtime.getInstance().getOption("auto-open").equals("true")) {
                try {
                    java.lang.Runtime.getRuntime().exec(new String[] {
                            Runtime.getInstance().getOption("pdf-viewer"), file.getAbsolutePath() });
                } catch (IOException e) {
                    try {
                        Desktop.getDesktop().open(file);
                    } catch (IOException e1) {
                        UI.displayError(_("No pdf viewer could be found!"));
                    }
                }
            }
        } else {
            preTemplateFile.delete();
        }
    }
}

From source file:de.aidger.utils.pdf.BalanceReportConverter.java

License:Open Source License

/**
 * Places the created document onto the template for this report.
 * /*from   w  w  w  .j  a v a2  s.c om*/
 * @param file
 *            The file to which this report will be saved.
 * @param preTemplateFile
 *            The report to be used.
 */
private boolean applyTemplate(File file, File preTemplateFile) {
    FileOutputStream outStream = null;
    FileInputStream inStream = null;
    PdfContentByte contentByte = null;
    PdfReader reader = null, templateReader = null;
    try {
        /*
         * Use the template located in the configuration path first, if it
         * exists.
         */
        File template = new File(
                Runtime.getInstance().getConfigPath() + "/templates/BalanceReportTemplate.pdf");
        URL templateURL = null;
        if (template.exists()) {
            templateURL = template.toURI().toURL();
        } else {
            templateURL = getClass().getResource("/de/aidger/res/pdf/BalanceReportTemplate.pdf");
        }
        if (templateURL == null) {
            throw new FileNotFoundException(_("The report template could not be loaded.") + " "
                    + _("Please make sure that a fitting template exists in the template folder."));
        }
        Document document = new Document(PageSize.A4.rotate());
        outStream = new FileOutputStream(file.getPath());
        inStream = new FileInputStream(preTemplateFile);
        writer = PdfWriter.getInstance(document, outStream);
        document.open();
        contentByte = writer.getDirectContent();
        reader = new PdfReader(inStream);
        templateReader = new PdfReader(templateURL);
        /*
         * Add the template pdf to the document and place the finished
         * report on top of it.
         */
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(templateReader, 1);
            int rotation = templateReader.getPageRotation(1);
            if (rotation == 90 || rotation == 270) {
                //landscape mode
                contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight());
            } else {
                //portrait mode
                contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
            page = writer.getImportedPage(reader, i);
            rotation = reader.getPageRotation(i);
            if (rotation == 90 || rotation == 270) {
                //landscape mode
                contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight());
            } else {
                //portrait mode
                contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
        }
        document.close();
        return true;
    } catch (FileNotFoundException e) {
        if (e.getMessage() != null) {
            UI.displayError(e.getMessage());
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:de.aidger.utils.pdf.BudgetReportConverter.java

License:Open Source License

/**
 * Initializes this BalanceReportConverter with a given file and filters for
 * the courses./*from   www. j av  a  2  s.  c om*/
 * 
 * @param file
 *            The file to create the pdf in.
 * @param filters
 *            The filters with which to filter the courses.
 */
public BudgetReportConverter(File file, BudgetFilter filters) {
    document = new Document(PageSize.A4);
    document.setMargins(document.leftMargin(), document.rightMargin(), document.topMargin() + 40,
            document.bottomMargin());
    this.filters = filters;
    file = checkExtension(file);
    name = _("Budget report");
    File preTemplateFile = null;
    try {
        preTemplateFile = File.createTempFile("BudgetReport", ".pdf");
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    makeNewDocument(preTemplateFile);
    if (fileCreated) {
        createCourses();
        document.close();
        if (applyTemplate(file, preTemplateFile)) {
            preTemplateFile.delete();
            /*
             * Open the created document if the setting is enabled with the
             * specified pdf viewer.
             */
            if (Runtime.getInstance().getOption("auto-open").equals("true")) {
                try {
                    java.lang.Runtime.getRuntime().exec(new String[] {
                            Runtime.getInstance().getOption("pdf-viewer"), file.getAbsolutePath() });
                } catch (IOException e) {
                    try {
                        Desktop.getDesktop().open(file);
                    } catch (IOException e1) {
                        UI.displayError(_("No pdf viewer could be found!"));
                    }
                }
            }
        } else {
            preTemplateFile.delete();
        }
    }
}

From source file:de.aidger.utils.pdf.BudgetReportConverter.java

License:Open Source License

/**
 * Places the created document onto the template for this report.
 * //  w ww  .j  a v a 2 s .co  m
 * @param file
 *            The file to which this report will be saved.
 * @param preTemplateFile
 *            The report to be used.
 */
private boolean applyTemplate(File file, File preTemplateFile) {
    FileOutputStream outStream = null;
    FileInputStream inStream = null;
    PdfContentByte contentByte = null;
    PdfReader reader = null, templateReader = null;
    try {
        /*
         * Use the template located in the configuration path first, if it
         * exists.
         */
        File template = new File(Runtime.getInstance().getConfigPath() + "/templates/BudgetReportTemplate.pdf");
        URL templateURL = null;
        if (template.exists()) {
            templateURL = template.toURI().toURL();
        } else {
            templateURL = getClass().getResource("/de/aidger/res/pdf/BudgetReportTemplate.pdf");
        }
        if (templateURL == null) {
            throw new FileNotFoundException(_("The report template could not be loaded.") + " "
                    + _("Please make sure that a fitting template exists in the template folder."));
        }
        Document document = new Document(PageSize.A4);
        outStream = new FileOutputStream(file.getPath());
        inStream = new FileInputStream(preTemplateFile);
        writer = PdfWriter.getInstance(document, outStream);
        document.open();
        contentByte = writer.getDirectContent();
        reader = new PdfReader(inStream);
        templateReader = new PdfReader(templateURL);
        /*
         * Add the template pdf to the document and place the finished
         * report on top of it.
         */
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(templateReader, 1);
            int rotation = templateReader.getPageRotation(1);
            if (rotation == 90 || rotation == 270) {
                //landscape mode
                contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight());
            } else {
                //portrait mode
                contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
            page = writer.getImportedPage(reader, i);
            rotation = reader.getPageRotation(i);
            if (rotation == 90 || rotation == 270) {
                //landscape mode
                contentByte.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(1).getHeight());
            } else {
                //portrait mode
                contentByte.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
        }
        document.close();
        return true;
    } catch (FileNotFoundException e) {
        if (e.getMessage() != null) {
            UI.displayError(e.getMessage());
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}