Example usage for com.lowagie.text DocumentException DocumentException

List of usage examples for com.lowagie.text DocumentException DocumentException

Introduction

In this page you can find the example usage for com.lowagie.text DocumentException DocumentException.

Prototype

public DocumentException(String message) 

Source Link

Document

Constructs a DocumentException with a message.

Usage

From source file:androidGLUESigner.pdf.PDFSignerEngine.java

License:Open Source License

/**
 * Finalize signature with timestamp and store into result file
 * @param signedHash the signed hash value
 * @param inputStream the stream to the input pdf file
 * @param outputStream the stream to the output pdf file
 * @throws Exception//from   www.ja va 2s.c  o m
 */
public void finalizeSign(byte[] signedHash, InputStream inputStream, OutputStream outputStream)
        throws Exception {

    // Create a temporary file
    File tmpFile = File.createTempFile("PDFSigner-", ".pdf");
    //tmpFile.deleteOnExit();

    // Save the PDF in the temporary file
    UtilityHelper.copyStream(inputStream, new FileOutputStream(tmpFile));

    // Add a timestamp:
    TSAClient tsc = new TSAClientBouncyCastle(tsa_url, tsa_login, tsa_passw);

    // Create the signature
    PdfPKCS7 sgn = new PdfPKCS7(null, getCertificateChain(), null, hashAlgo, null, true);
    sgn.setExternalDigest(signedHash, hash, "RSA");
    byte[] encodedSig = sgn.getEncodedPKCS7(hash, calendar, tsc, ocsp);
    System.out.println("finelizeSign: signedHash.length    = " + signedHash.length);
    System.out.println("finelizeSign: encodedSig.length    = " + encodedSig.length);

    if (SIGNATURE_MAX_SIZE + 2 < encodedSig.length)
        throw new DocumentException("Not enough space");

    String encodedSigHex = UtilityHelper.byteArrayToHexString(encodedSig);

    byte[] placeHolder = getPlaceHolder(SIGNATURE_MAX_SIZE * 2).getBytes();

    byte[] paddedSig = new byte[placeHolder.length];
    // fill with harmless data
    for (int i = 0; i < paddedSig.length; i++)
        paddedSig[i] = 0x30;

    System.out.println("finelizeSign: placeHolder.length   = " + placeHolder.length);
    System.out.println("finelizeSign: encodedSigHex.length = " + encodedSigHex.length());
    assert (placeHolder.length == paddedSig.length);

    System.arraycopy(encodedSigHex.getBytes(), 0, paddedSig, 0, encodedSigHex.getBytes().length);

    // Replace the contents
    FilePatchHelper.replace(tmpFile.getPath(), placeHolder, paddedSig);

    // Save the PDF in the outputStream
    UtilityHelper.copyStream(new FileInputStream(tmpFile), outputStream);
    tmpFile.delete();
}

From source file:classroom.filmfestival_c.Movies21.java

@SuppressWarnings("unchecked")
public static void main(String args[]) {
    Movies18.main(args);//w  ww  . ja v  a  2  s .co  m
    Movies20.main(args);
    try {
        PdfReader reader1 = new PdfReader(Movies18.RESULT);
        List<Map> list1 = SimpleBookmark.getBookmark(reader1);
        int[] offsets1 = new int[list1.size() + 1];
        int count = 0;
        for (Map<String, String> mark : list1) {
            offsets1[count++] = getPageNumber(mark.get("Page"));
        }
        offsets1[count] = reader1.getNumberOfPages() + 1;
        PdfReader reader2 = new PdfReader(Movies20.RESULT);
        List<Map> list2 = SimpleBookmark.getBookmark(reader2);
        if (list2.size() != list1.size()) {
            throw new DocumentException("The documents don't have the same number of bookmark entries.");
        }
        int[] offsets2 = new int[list2.size() + 1];
        count = 0;
        for (Map<String, String> mark : list2) {
            offsets2[count++] = getPageNumber(mark.get("Page"));
        }
        offsets2[count] = reader2.getNumberOfPages() + 1;
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
        document.open();
        for (int i = 0; i < list1.size(); i++) {
            for (int j = offsets1[i]; j < offsets1[i + 1]; j++) {
                copy.addPage(copy.getImportedPage(reader1, j));
            }
            for (int j = offsets2[i]; j < offsets2[i + 1]; j++) {
                copy.addPage(copy.getImportedPage(reader2, j));
            }
        }
        document.close();
    } catch (IOException e) {
        LOGGER.warn("IOException: " + e);
    } catch (DocumentException e) {
        LOGGER.warn("IOException: " + e);
    }
}

From source file:com.hotaviano.tableexporter.csv.CSVExporter.java

License:Open Source License

private Document createDocument(String html) throws DocumentException {
    StringTableParser parser = new DefaultStringTableParser();

    try {/*from   w w  w. ja v a2  s  . co  m*/
        return parser.parse(html);
    } catch (JDOMException | IOException ex) {
        throw new DocumentException(ex);
    }
}

From source file:com.hotaviano.tableexporter.docx.DOCXExporter.java

License:Open Source License

@Override
public byte[] export(String htmlTable) throws DocumentException {
    XWPFDocument doc = new XWPFDocument();

    Document document = createDocument(htmlTable);

    int cols = getHeaderSize(document);
    int rows = getHeaderSize(document) + 1;

    XWPFTable table = doc.createTable(rows, cols);

    createHeaderTable(table, document);// www  . j  a  v  a2s  .c  o  m
    createBodyTable(table, document);

    CTTblWidth width = table.getCTTbl().addNewTblPr().addNewTblW();
    width.setType(STTblWidth.DXA);
    width.setW(BigInteger.valueOf(9072));

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        doc.write(out);
        out.close();
    } catch (IOException ex) {
        throw new DocumentException(ex);
    }

    return out.toByteArray();
}

From source file:com.hotaviano.tableexporter.pdf.PDFExporter.java

License:Open Source License

@Override
public byte[] export(String htmlTable) throws DocumentException {
    com.lowagie.text.Document doc = new com.lowagie.text.Document();

    Document document = null;/*from   w w  w .  j  a  v a  2  s  .c om*/
    try {
        document = parser.parse(htmlTable);
    } catch (JDOMException | IOException ex) {
        throw new DocumentException(ex);
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PdfWriter.getInstance(doc, out);

    doc.open();

    PdfPTable table = new PdfPTable(columnLength(document));

    List<PdfPCell> cells = getHeaders(document);
    for (PdfPCell cell : cells) {
        table.addCell(cell);
    }

    List<String> data = getBodyValues(document);
    for (String item : data) {
        table.addCell(new PdfPCell(new Phrase(item)));
    }

    doc.add(table);
    doc.close();

    return out.toByteArray();
}

From source file:com.hotaviano.tableexporter.xls.XLSExporter.java

License:Open Source License

@Override
public byte[] export(String htmlTable) throws DocumentException {
    Document document = createDocument(htmlTable);

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();/*ww w.  ja va  2s  .c  om*/

    CellStyle headerStyle = createHeaderStyle(wb);

    Element theadTr = document.getRootElement().getChild("thead").getChildren().get(0);
    Element tbody = document.getRootElement().getChild("tbody");

    createHeader(sheet.createRow(0), theadTr, headerStyle);
    createBody(sheet, tbody);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        wb.write(out);
    } catch (IOException ex) {
        throw new DocumentException(ex);
    }

    return out.toByteArray();
}

From source file:com.jk.framework.pdf.PDFUtil.java

License:Apache License

/**
 * Creates the font.//ww w  .  j  av  a  2  s  .c o  m
 *
 * @param fontName
 *            the font name
 * @param size
 *            the size
 * @param fontStyle
 *            the font style
 * @return the font
 * @throws DocumentException
 *             the document exception @1.1
 */
public static Font createFont(final String fontName, final int size, final boolean fontStyle)
        throws DocumentException {
    BaseFont baseFont;
    Font font = null;
    try {
        baseFont = BaseFont.createFont("c:/windows/fonts/" + fontName + ".ttf", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);
        if (fontStyle == true) {
            font = new Font(baseFont, size, Font.BOLD);
        } else {
            font = new Font(baseFont, size, Font.NORMAL);
        }
        // return new Font(baseFont, size);
        return font;
    } catch (final IOException e) {
        throw new DocumentException(e);
    }
}

From source file:com.khs.report.writer.ReportPDFWriter.java

License:Apache License

private void calculateRelativeSizes(PdfPTable table) throws DocumentException {
    float total = 0;
    int numCols = colWidths.length;
    for (int k = 0; k < numCols; ++k) {
        total += colWidths[k];//from  w  w  w .  j  a v a 2  s .  c om
    }
    if (total > document.getPageSize().getWidth()) {
        throw new DocumentException("Table size is greater than page width.");
    }
    float[] relativeWidths = new float[colWidths.length];
    for (int k = 0; k < numCols; ++k) {
        relativeWidths[k] = 100 * colWidths[k] / total;
    }
    table.setWidths(relativeWidths);
    float widthPercentage = total / document.getPageSize().getWidth() * 100;
    table.setWidthPercentage(widthPercentage);

}

From source file:datasoul.servicelist.ServiceListExporterPanel.java

License:Open Source License

private void exportSlides(String fileName) throws FileNotFoundException, DocumentException, Exception {

    // Determine width and height. Use from the template for the first item
    ServiceItem item = ServiceListTable.getActiveInstance().getServiceItem(0);
    if (item == null)
        return;//from ww w  .j a  va 2 s . c o  m

    DisplayTemplate firstTemplate = TemplateManager.getInstance().newDisplayTemplate(item.getTemplate());
    int width = firstTemplate.getWidth();
    int height = firstTemplate.getHeight();

    // Create output
    ServiceListExporterSlides sles = new ServiceListExporterSlides(fileName, width, height);
    try {
        ServiceListTable slt = ServiceListTable.getActiveInstance();
        ContentRender r = sles.getRender();
        ImageListServiceRenderer img = new ImageListServiceRenderer();
        img.setImageWithoutTempFile(BackgroundConfig.getInstance().getBackgroundImg());
        r.paintBackground(img);
        int slideCount = 0;

        /* initial empty slide */
        if (cbEmptySlide.isSelected()) {
            sles.addEmptySlide();
            slideCount++;
        }

        pbProgress.setMaximum(slt.getRowCount());
        for (int i = 0; i < slt.getRowCount(); i++) {
            Object o = slt.getServiceItem(i);
            pbProgress.setValue(i);
            if (o instanceof Song) {
                Song s = (Song) o;
                r.setTemplate(s.getTemplate());
                r.setTitle(s.getTitle());
                r.setSongAuthor(s.getSongAuthor());
                r.setSongSource(s.getSongSource());
                r.setCopyright(s.getCopyright());
                for (int k = 0; k < s.getRowCount(); k++) {
                    slideCount++;
                    r.setSlide(s.getSlideText(k));
                    if (k < s.getRowCount() - 1) {
                        r.setNextSlide(s.getSlideText(k + 1));
                    } else {
                        r.setNextSlide("");
                    }
                    /* start rendering */
                    r.slideChange(-1);
                    /* wait render thread to render the slide */
                    while (slideCount > sles.getSlideCount()) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException ex) {
                            // ignore
                        }
                        if (sles.getSlideCount() == -1) {
                            throw new DocumentException(java.util.ResourceBundle
                                    .getBundle("datasoul/internationalize").getString("INTERNAL ERROR"));
                        }
                    }
                }
                /* empty slide after songs */
                if (cbEmptySlide.isSelected()) {
                    sles.addEmptySlide();
                    slideCount++;
                }

            } else if (o instanceof TextServiceItem) {
                TextServiceItem t = (TextServiceItem) o;
                r.setTemplate(t.getTemplate());
                r.setTitle(t.getTitle());
                for (int k = 0; k < t.getRowCount(); k++) {
                    slideCount++;
                    r.setSlide(t.getSlideText(k));
                    if (k < t.getRowCount() - 1) {
                        r.setNextSlide(t.getSlideText(k + 1));
                    } else {
                        r.setNextSlide("");
                    }
                    /* start rendering */
                    r.slideChange(-1);
                    /* wait render thread to render the slide */
                    while (slideCount > sles.getSlideCount()) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException ex) {
                            // ignore
                        }
                        if (sles.getSlideCount() == -1) {
                            throw new DocumentException(java.util.ResourceBundle
                                    .getBundle("datasoul/internationalize").getString("INTERNAL ERROR"));
                        }
                    }
                }
                /* empty slide after text */
                if (cbEmptySlide.isSelected()) {
                    sles.addEmptySlide();
                    slideCount++;
                }

            }
        }
        pbProgress.setValue(slt.getRowCount());
        sles.write();

    } finally {
        sles.cleanup();
    }

}

From source file:forseti.reportes.JReportesDlg.java

License:Open Source License

@SuppressWarnings({ "rawtypes" })
private String VerifyFilerClause(StringBuffer select, HttpServletRequest request)
        throws ServletException, IOException, DocumentException {
    //System.out.println("------------------------------------------------------------------------------------");
    int totalatrs = 0, totalfil = 0;

    JReportesBindFSet setF = new JReportesBindFSet(request);
    setF.m_Where = "ID_Report = '" + p(request.getParameter("REPID")) + "'";
    setF.m_OrderBy = "ID_Column ASC";
    setF.Open();//ww w.j  av  a 2  s  . co m

    int initial = select.indexOf("[", 0);
    int fin = (initial == -1) ? -1 : select.indexOf("]", initial);

    while (initial != -1 && fin != -1) {
        String atr = select.substring(initial + 1, fin); // ej ID_Empleado
        totalatrs += 1;
        //System.out.println("ATRIBUTO: " + atr + " Ini: " + (initial+1) + " Fin: " + fin);
        Enumeration nombresAtr = request.getParameterNames();
        while (nombresAtr.hasMoreElements()) {
            String nombreAtr = (String) nombresAtr.nextElement();

            if (atr.equals(nombreAtr)) {
                totalfil += 1;
                //System.out.println(nombreAtr);
            }
        }
        initial = select.indexOf("[", fin);
        fin = (initial == -1) ? -1 : select.indexOf("]", initial);
    }

    if (totalatrs != totalfil)
        throw new DocumentException(
                "Intento de inyeccin SQL detectada. El total de atributos no coincide con el total de elementos del filtro, se ha registrado tu usuario y host desde el cual estas queriendo corromper el sistema");

    //System.out.println("-----------------------" + totalatrs + " : " + totalfil + "------------------------");

    initial = select.indexOf("[", 0);
    fin = (initial == -1) ? -1 : select.indexOf("]", initial);

    while (initial != -1 && fin != -1) {
        String key = select.substring(initial + 1, fin); // ej ID_Empleado

        // Carga los valores por default
        Enumeration nombresAtr = request.getParameterNames();
        while (nombresAtr.hasMoreElements()) {
            String nombreAtr = (String) nombresAtr.nextElement();
            String valorAtr = (String) request.getParameter(nombreAtr);
            if (nombreAtr.equals(key)) {
                if (valorAtr.matches("\\d{1,2}/(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/\\d{4}")) // Es fecha....
                    valorAtr = JUtil.obtFechaSQL(valorAtr);
                //System.out.println(select + "\n");
                //System.out.println("KV:"  + nombreAtr  + "|"  + valorAtr + "\n");
                for (int i = 0; i < setF.getNumRows(); i++) {
                    if (setF.getAbsRow(i).getPriDataName().equals(nombreAtr)) {
                        //System.out.println("FILTRO1:" + nombreAtr  + "|"  + setF.getAbsRow(i).getPriDefault() + "\n");
                        if (!setF.getAbsRow(i).getFromCatalog()) // No es de catalogo
                        {
                            if (setF.getAbsRow(i).getPriDefault().length() > 0
                                    && setF.getAbsRow(i).getPriDefault().substring(0, 1).equals("[")) //Es lista de seleccion
                            {
                                //En filtros de seleccin, verificar que efectivamente exista la seleccin. Si no existe, significa intento de inyeccin SQL a travs de la modificacin directa del codigo html del filtro
                                if (!JUtil.verificarElementoDeFiltro(setF.getAbsRow(i).getPriDefault(),
                                        valorAtr))
                                    throw new DocumentException(
                                            "Intento de inyeccin SQL detectada, se ha registrado tu usuario y host desde el cual estas queriendo corromper el sistema");
                                select.replace(initial, fin + 1, valorAtr);
                            } else
                                select.replace(initial, fin + 1, q(valorAtr)); //Como es captura directa, utiliza q() para agregar escapes de ' al valor introducido por el usuario para evitar errores de sql o intentos de ataques de inyeccin sql
                        } else // Si es de catalogo
                        {
                            select.replace(initial, fin + 1, valorAtr);
                        }
                    }
                    if (setF.getAbsRow(i).getSecDataName().equals(nombreAtr)) {
                        //System.out.println("FILTRO2:" + nombreAtr  + "|"  + setF.getAbsRow(i).getSecDefault() + "\n");
                        if (!setF.getAbsRow(i).getFromCatalog()) // No es de catalogo
                        {
                            if (setF.getAbsRow(i).getSecDefault().length() > 0
                                    && setF.getAbsRow(i).getSecDefault().substring(0, 1).equals("[")) //Es lista de seleccion
                            {
                                //En filtros de seleccin, verificar que efectivamente exista la seleccin. Si no existe, significa intento de inyeccin SQL a travs de la modificacin directa del codigo html del filtro
                                if (!JUtil.verificarElementoDeFiltro(setF.getAbsRow(i).getSecDefault(),
                                        valorAtr))
                                    throw new DocumentException(
                                            "Intento de inyeccin SQL detectada, se ha registrado tu usuario y host desde el cual estas queriendo corromper el sistema");
                                select.replace(initial, fin + 1, valorAtr);
                            } else
                                select.replace(initial, fin + 1, q(valorAtr)); //Como es captura directa, utiliza q() para agregar escapes de ' al valor introducido por el usuario para evitar errores de sql o intentos de ataques de inyeccin sql
                        } else // Si es de catalogo
                        {
                            select.replace(initial, fin + 1, valorAtr);
                        }
                    }
                }
            }
        }

        initial = select.indexOf("[", 0);
        fin = (initial == -1) ? -1 : select.indexOf("]", initial);
    }

    return select.toString();

}