I’m having trouble with vector graphics in my PDF generation project using iText for Java. The colors get messed up when I try to add SVG files to my documents.
I need to create PDFs that include vector graphics along with text content. I’m using iText library which works great for most things. My graphics were made in Adobe Illustrator originally, but since iText doesn’t support AI files directly, I converted them to SVG format. Unfortunately, the SVG rendering has problems where some colors don’t show up correctly.
Here’s my test code that shows the problem:
Maven setup:
<dependencies>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>9.0.0</version>
<type>pom</type>
</dependency>
</dependencies>
Java implementation:
package com.example.pdftest;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.svg.converter.SvgConverter;
import java.io.FileInputStream;
public class PdfGenerator {
public static void main(String[] args) throws Exception {
String vectorFile = "C:\\graphics\\company_logo.svg";
String resultFile = "C:\\output\\final_document.pdf";
try (FileInputStream vectorStream = new FileInputStream(vectorFile)) {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(resultFile));
Image vectorImage = SvgConverter.convertToImage(vectorStream, pdfDoc)
.setWidth(150)
.setHorizontalAlignment(HorizontalAlignment.CENTER);
Paragraph content = new Paragraph("Document content here...").setFontSize(18);
Document doc = new Document(pdfDoc);
doc.add(vectorImage);
doc.add(content);
doc.close();
}
}
}
The output PDF has completely wrong colors compared to the original SVG. I’m thinking maybe I should try embedding the AI files directly as PDF components instead of converting to SVG first. Since AI files are basically PDF format, this might work better. I know tools like LaTeX can include PDF files as figures, so there should be a way to do this with iText too.
Is there a method to embed vector graphics directly without creating new pages? Or does anyone know how to fix the SVG color rendering issue?