how to add svg in pdf document iText - java

I'm using iTextRenderer() to convert html (String) to pdf file. I would like to add on end pdf file, image as svg. I'm using JFreeChart to create SVG File.
File file = new File("D:\\testowy.txt"); //html in string
File outPDF = new File("D:\\testww.pdf"); //output pdf
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(IOUtils.readUtf(file));
renderer.layout();
renderer.createPDF(new BufferedOutputStream(new FileOutputStream(outPDF)));
Below picture shows how appearance my pdf. The svg file doesnt creat correct.
The text "7e5a7f..." is a SVG.
I tried use framework PDF, but the text is skip and only svg is created.
PdfDocument doc = new PdfDocument(
new PdfWriter(new FileOutputStream(outPDF),
new WriterProperties().setCompressionLevel(0)));
doc.addNewPage();
SvgConverter.drawOnDocument(IOUtils.readUtf(file), doc, 1);
doc.close();

Related

Merging Documents iText7

I am adding text to an existing pdf.
My code so far will add the text to the file but it deletes the original content that was on the pdf before, does anyone know how to fix this? So that the added text is on a new page and the original content of the pdf is on another page.
String field1 = ("/Users/Desktop/") + selectedFile.getName();
System.out.println(field1);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(field1));
PdfPage page = pdfDoc.addNewPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(1,1, 600, 843);
pdfCanvas.rectangle(rectangle);
pdfCanvas.stroke();
Canvas canvas = new Canvas( pdfCanvas, pdfDoc, rectangle);
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter text to add");
String addText = myObj.nextLine(); // Read user input
Paragraph p = new Paragraph(addText);
Scanner myObj1 = new Scanner(System.in); // Create a Scanner object
PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
p.setFont(font);
canvas.add(p);
pdfDoc.close();
canvas.close();
With PdfDocument pdfDoc = new PdfDocument(new PdfWriter(field1)) you will always create a new document with new content. You are now ignoring the original content. You must open the PDF in stamping mode.
Refer to the iText API: https://api.itextpdf.com/iText7/java/7.1.4/com/itextpdf/kernel/pdf/PdfDocument.html
Constructor and Description
PdfDocument(PdfReader reader)
Open PDF document in reading mode.
PdfDocument(PdfReader reader, DocumentProperties properties)
Open PDF document in reading mode.
PdfDocument(PdfReader reader, PdfWriter writer)
Opens PDF document in the stamping mode.
PdfDocument(PdfReader reader, PdfWriter writer, StampingProperties properties)
Open PDF document in stamping mode.
PdfDocument(PdfWriter writer)
Open PDF document in writing mode.
PdfDocument(PdfWriter writer, DocumentProperties properties)
Open PDF document in writing mode.

Problem with Converting from photo to PDF

I have a problem with converting from png/jpg to pdf ... Everytime I try to convert it the pdf document doesnt take the full size of the png/jpg photo like the photo below.. and this is my converting code.. I am using itextpdf lib.
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream("C:\\AFKO Fatura\\fatura.pdf"));
document.open();
Image image2 = Image.getInstance("C:\\AFKO FATURA\\fatura.jpg");
document.add(image2);
document.close();`

SVG to PNG with Apache Batik then attach to PDF with PDFBox without saving images

So as the title says I am looking for a way to turn SVG to PNG with Apache Batik and then attach this image to PDF file using PDFBox without actually creating the svg and png anywhere.
Currently I have a web form that has SVG image with selectable parts of it.
When the form is submitted I take the "html" part of the svg meaning I keep something like <svg bla bla> <path bla bla/></svg> in a string that Spring then uses to create a ".svg" file in a given folder, then Batik creates a PNG file in the same folder and then PDFBox attaches it to the PDF - this works fine(code below).
//Get the svg data from the Form and Create the svg file
String svg = formData.getSvg();
File svgFile = new File("image.svg");
BufferedWriter writer = new BufferedWriter(new FileWriter(svgFile));
writer.write(svg);
writer.close();
// Send to Batik to turn to PNG
PNGTranscoder pngTranscode = new PNGTranscoder();
File svgFile = new File("image.svg");
InputStream in = new FileInputStream(svgFile);
TranscoderInput tIn = new TranscoderInput(in);
OutputStream os = new FileOutputStream("image.png");
TranscoderOutput tOut = new TranscoderOutput(os)
pngTranscode .transcode(tIn , tOut);
os.flush();
os.close();
//Send to PDFBox to attach to pdf
File pngfile = new File("image.png");
String path = pngfile.getAbsolutePath();
PDImageXObject pdImage = PDImageXObject.createFromFile(path, pdf);
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(1));
contents.drawImage(pdImage, 0, pdf.getPage(1).getMediaBox().getHeight() - pdImage.getHeight());
contents.close();
As you can see there are a lot of files and stuff (need to tidy it up a bit), but is it possible to do this on the run without the creation and constant fetching of the svg and png files?
Given the suggestion in the comments I opted for using ByteArrayOutputStream, ByteArrayInputStream, BufferedImage and LosslessFactory. Its a bit slower than the saving (if you go through it in debug as seems the BufferedImage goes on a holiday first before creating the image).
The sources I found to use are: How to convert SVG into PNG on-the-fly and Print byte[] to pdf using pdfbox
byte[] streamBytes = IOUtils.toByteArray(new ByteArrayInputStream(formData.getSvg().getBytes()));
PNGTranscoder pngTranscoder = new PNGTranscoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
pngTranscoder.transcode(new TranscoderInput(new ByteArrayInputStream(streamBytes)), new TranscoderOutput(os));
InputStream is = new ByteArrayInputStream(os.toByteArray());
BufferedImage bim = ImageIO.read(is);
PDImageXObject pdImage = LosslessFactory.createFromImage(pdf, bim);
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(1));
contents.drawImage(pdImage, 0, pdf.getPage(1).getMediaBox().getHeight() - pdImage.getHeight());
contents.close();
Based on the comments and links provided by D.V.D., I also worked through the problem. I just wanted to post the simple but full example, for anyone wanting to review in the future.
public class App {
private static String OUTPUT_PATH = "D:\\so52875145\\output\\PdfWithPngImage.pdf";
public static void main(String[] args) {
try {
// obtain the SVG source (hardcoded here, but the OP would obtain the String from form data)
byte[] svgByteArray = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><polygon points=\"200,10 250,190 160,210\" style=\"fill:lime;stroke:purple;stroke-width:1\" /></svg>".getBytes();
System.out.println("Converted svg to byte array...");
// convert SVG into PNG image
PNGTranscoder pngTranscoder = new PNGTranscoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
pngTranscoder.transcode(new TranscoderInput(new ByteArrayInputStream(svgByteArray)), new TranscoderOutput(os));
System.out.println("Transcoded svg to png...");
// create PDF, and add page to it
PDDocument pdf = new PDDocument();
pdf.addPage(new PDPage());
// generate in-memory PDF image object, using the transcoded ByteArray stream
BufferedImage bufferedImage = ImageIO.read( new ByteArrayInputStream(os.toByteArray()) );
PDImageXObject pdImage = LosslessFactory.createFromImage(pdf, bufferedImage);
System.out.println("Created PDF image object...");
// write the in-memory PDF image object to the PDF page
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(0));
contents.drawImage(pdImage, 0, 0);
contents.close();
System.out.println("Wrote PDF image object to PDF...");
pdf.save(OUTPUT_PATH);
pdf.close();
System.out.println("Saved PDF to path=[" + OUTPUT_PATH + "]");
}
catch (Exception e) {
e.printStackTrace();
}
}
}

iText add image to pdf - setAbsolutePosition [duplicate]

I am trying to read one PDF and copy its data into another PDF. The first PDF contains some text and images and I wish to write an image in the second PDF exactly where the text ends(which is basically the end of the PDF file). RIght now it just prints at the top. How can I make this change?
PdfReader reader = null;
reader = new PdfReader(Var.input);
Document document=new Document();
PdfWriter writer = null;
writer = PdfWriter.getInstance(document,new FileOutputStream(Var.output));
PdfImportedPage page = writer.getImportedPage(reader, 1);
reader.close();
document.open();
PdfContentByte cb = writer.getDirectContent();
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
Image image = null;
image = Image.getInstance (Var.qr);
document.add(image);
document.close();
Try this:
First get the location/co-ords of where the image needs to go, then simply add the second line from below to your code so the image is inserted at that location "X, Y"
Image image = Image.getInstance(String RESOURCE);
image.setAbsolutePosition(X, Y);
writer.getDirectContent().addImage(image);
Take a look here for some examples in iText 5: https://itextpdf.com/en/resources/examples/itext-5-legacy/chapter-3-adding-content-absolute-positions
You should use a PdfStamper instead of a PdfWriter with imported pages. Your approach throws away all interactive contents. You can use sorifiend's idea there, too.
To determine where the text on the given page ends, have a look at the iText in Action, 2nd edition example ShowTextMargins which parses a PDF and ads a rectangle showing the text margin.

Cant adding a TIFF to a pdf using PDFBox

Im trying to add a TIFF image (CCIT Group 3) to a PDF using Java and PDFBox 1.8.10. There is an image shown on the output file, but its displayed wrong. Its only some black and white pixels.
String outputPath = "/tmp/PDFImage.pdf";
String imagePath = "/tmp/header.tif";
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream content = new PDPageContentStream(doc, page);
PDXObjectImage ximage = new PDCcitt(doc, new RandomAccessFile(new File(imagePath), "r"));
content.drawImage(ximage, 0, 500);
content.close();
doc.save(outputPath);
doc.close();
The PDFBox dependencies says : To write TIFF images a JAI ImageIO Core library will be needed.
I imported the library and and scanned for plugins, but dont found an example how to use is exactly. Someone can help ?

Categories