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