使用IText7将SVG图像添加到PDF

时间:2017-05-27 11:34:35

标签: itext7

我正在使用iText7生成PDF文件。我需要帮助将svg文件添加到PDF文档中。需要使用URL从远程位置获取svg文件。

1 个答案:

答案 0 :(得分:1)

我能够使用apache batik库来实现这一点。这是我如何做到的。

Maven依赖

<dependency>
    <groupId>org.apache.xmlgraphics</groupId>
    <artifactId>batik-transcoder</artifactId>
    <version>1.9</version>
</dependency>

自定义ITagWorker for SvgImage

import com.itextpdf.html2pdf.attach.ITagWorker;
import com.itextpdf.html2pdf.attach.ProcessorContext;
import com.itextpdf.html2pdf.html.node.IElementNode;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.layout.IPropertyContainer;
import com.itextpdf.layout.element.Image;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;

import java.io.ByteArrayOutputStream;

public class SvgImageWorker implements ITagWorker {

    private Image img;

    @Override
    public void processEnd(IElementNode iElementNode, ProcessorContext processorContext) {
        String url = iElementNode.getAttribute("src");

        JPEGTranscoder jpegTranscoder = new JPEGTranscoder();

        // Set the transcoding hints.
        jpegTranscoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8));

        // Create the transcoder input.
        try {
            TranscoderInput input = new TranscoderInput(url);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(10000);
            TranscoderOutput output = new TranscoderOutput(byteArrayOutputStream);

            // Save the image.
            jpegTranscoder.transcode(input, output);

            img = new Image(ImageDataFactory.create(byteArrayOutputStream.toByteArray()));
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean processContent(String s, ProcessorContext processorContext) {
        return false;
    }

    @Override
    public boolean processTagChild(ITagWorker iTagWorker, ProcessorContext processorContext) {
        return false;
    }

    @Override
    public IPropertyContainer getElementResult() {
        return img;
    }

}