Добавить аннотацию вложения в pdf и выполнить в jar веб-приложения - PullRequest
0 голосов
/ 22 мая 2018

Я реализую добавление аннотации вложения в pdf, используя аннотацию itext, но очень забавно, что из-за ограничений среды веб-приложения я должен поместить коды реализации и файл вложения в файл jar.Вот краткая иерархия реализации:

  1. package example.pdf
    • Practice.java
    • attachment.doc

Основные коды:

protected void createAttachment(PdfWriter writer, Rectangle rect, String 
templatePath, String fileName) throws IOException, DocumentException {
// Get instruction document
String embed = 
getClass().getClassLoader().getResource(templatePath).getFile();

// The fileName here is used to display in the attachment list of the 
// document
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
            writer, embed, fileName, null);

// The fileName here is used to display on the document
PdfAnnotation attachment =
            PdfAnnotation.createFileAttachment(writer, rect, fileName, fs);

// Specify the width and height of the icon area
PdfAppearance app = writer.getDirectContent().createAppearance(200, 200);
String wordIcon = 
getClass().getClassLoader().getResource(WORD_ICON).getFile();
    Image img = Image.getInstance(wordIcon);
    img.scaleAbsolute(200, 200);
    img.setAbsolutePosition(0, 0);

    app.addImage(img);
    attachment.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, app);
    writer.addAnnotation(attachment);
}

Указанные выше коды будут вызываться классом обслуживания:

Rectangle rect = new Rectangle(220, 620, 250, 640);
    createAttachment(pdfWriter, rect, "pdf/attachment.doc", 
"attachment.doc");

Он работает нормально в моей среде IDE, но как только я сделал их какjar (включая вложение), кажется, вложение не может быть найдено / прикреплено веб-приложением.И сказал мне, что файл не может быть расположен в системном пути.

Я знаю, что это может быть проблема, связанная с механизмом определения пути к классам (например, загрузчик классов и метод загрузки), но это действительно заблокировало менядвигаться дальше, так как я не нашел никакого возможного решения.

Исключение:

java.io.FileNotFoundException: C:\Projects\work\test-1.3.6.0- 
SNAPSHOT.jar!\pdf\attachment.doc (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
at java.net.URL.openStream(URL.java:1045)
at com.lowagie.text.pdf.PdfFileSpecification.fileEmbedded(Unknown Source)
at com.lowagie.text.pdf.PdfFileSpecification.fileEmbedded(Unknown Source)
at com.lowagie.text.pdf.PdfFileSpecification.fileEmbedded(Unknown Source)
at example.pdf.Implementation.createAttachment

1 Ответ

0 голосов
/ 30 мая 2018

Проблема решена.Единственное отличие заключается в том, что вместо имени файла берется входной поток, для этого есть класс PdfFileSpecification.

        InputStream embedInputStream = 
        getClass().getClassLoader().getResourceAsStream(templatePath);

        byte[] buffer = new byte[1024];

        embedOutputStream = new ByteArrayOutputStream();
        int len = -1;
        while ((len = embedInputStream.read(buffer)) != -1) {
            embedOutputStream.write(buffer, 0, len);
        }

        // The fileName here is used to display in the attachment list of the document
        PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
                writer, null, fileName, embedOutputStream.toByteArray());

        // The fileName here is used to display on the document
        PdfAnnotation attachment =
                PdfAnnotation.createFileAttachment(writer, rect, fileName, fs);
...