I have been trying to add an image to a PDF document using iText 7.
The function I have created to add the image takes a ImageData type and then adds it to a rectangle on a canvas and add that to a PDF. however, I keep getting the error
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
and then
Caused by: java.io.FileNotFoundException: pdf.pdf (The requested operation cannot be performed on a file with a user-mapped section open)
The function code is:
protected void ExportToPdf(ImageData img) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader("pdf.pdf"), new PdfWriter("pdf.pdf"));
PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
PageSize ps = PageSize.A4;
Rectangle page = new Rectangle(ps.getWidth(),ps.getHeight());
canvas.addImage(img, page, true);
pdfDoc.close();
`
And my main is as follows:
public static void main(String[] args) throws IOException { //adds values to maps for the program to use
//starts PDF writer
PdfWriter writer = new PdfWriter("pdf.pdf");
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf);
pdf.addNewPage();
document.close();
writer.close();
pdf.close();
The full program takes a scene and converts it into an image and then feeds it into the function to be added to the PDF. The code for that is:
WritableImage img = new WritableImage(1000, 700);
scene.snapshot(img);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(img, null);
ImageData imgData = ImageDataFactory.create(SwingFXUtils.fromFXImage(img, null), null);
ExportToPdf(imgData);
Any help would be amazing, thank you.