itext pdf의 벡터 그래픽
문제
우리는 itext를 사용하여 Java에서 PDF를 생성합니다 (이 사이트의 일부 권장 사항 기반). 그러나 GIF와 같은 이미지 형식에 로고의 사본을 포함 시키면 사람들이 확대되거나 축소 될 때 약간 이상하게 보입니다.
이상적으로는 EPS, SVG 또는 PDF 템플릿과 같은 벡터 형식으로 이미지를 포함하고 싶습니다. 웹 사이트는 EPS 지원이 삭제되었다고 주장하며 PDF 내에 PDF 또는 PS를 포함 시키면 오류가 발생할 수 있으며 SVG를 언급하지도 않습니다.
우리의 코드는 ITEXT가 아닌 Graphics2D API를 사용하지만 AWT 모드를 벗어나 결과를 달성하면 ITEXT 자체를 기꺼이 사용합니다. 이 작업은 어떻게 할 수 있습니까?
해결책
에 따르면 선적 서류 비치 ITEXT는 JPEG, GIF, PNG, TIFF, BMP, WMF 및 EPS의 다음 이미지 형식을 지원합니다. 이것이 도움이 될지 모르겠지만 성공적으로 사용했습니다. itextsharp 벡터를 포함시키기 위해 WMF PDF 파일의 이미지 :
씨#:
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class Program
{
public static void Main()
{
Document document = new Document();
using (Stream outputPdfStream = new FileStream("output.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
using (Stream imageStream = new FileStream("test.wmf", FileMode.Open, FileAccess.Read, FileShare.Read))
{
PdfWriter.GetInstance(document, outputPdfStream);
Image wmf = Image.GetInstance(imageStream);
document.Open();
document.Add(wmf);
document.Close();
}
}
}
다른 팁
이것은 내가 여기서 찾은 게시물에서 파생 된 것과 공식적인 예입니다.
/**
* Reads an SVG Image file into an com.itextpdf.text.Image instance to embed it into a PDF
* @param svgPath SVG filepath
* @param writer PdfWriter instance
* @return Instance of com.itextpdf.text.Image holding the SVG file
* @throws IOException
* @throws BadElementException
*/
private static Image getSVGImage(String svgPath, PdfWriter writer) throws IOException, BadElementException {
SVGDocument svgDoc = new SAXSVGDocumentFactory(null).createSVGDocument(null, new FileReader(svgPath));
// Try to read embedded height and width
float svgWidth = Float.parseFloat(svgDoc.getDocumentElement().getAttribute("width").replaceAll("[^0-9.,]",""));
float svgHeight = Float.parseFloat(svgDoc.getDocumentElement().getAttribute("height").replaceAll("[^0-9.,]",""));
PdfTemplate svgTempl = PdfTemplate.createTemplate(writer, svgWidth, svgHeight);
Graphics2D g2d = new PdfGraphics2D(svgTempl, svgTempl.getWidth(), svgTempl.getHeight());
GraphicsNode chartGfx = (new GVTBuilder()).build(new BridgeContext(new UserAgentAdapter()), svgDoc);
chartGfx.paint(g2d);
g2d.dispose();
return new ImgTemplate(svgTempl);
}
이미지 인스턴스를 PDF에 쉽게 추가 할 수 있습니다 (내 경우 서명으로).
ITEXT 작성자가 Graphics2D API와 Apache Batik 라이브러리를 사용하여 PDF에서 SVG를 그리는 몇 가지 예를 찾았습니다.
http://itextpdf.com/examples/iia.php?id=269
http://itextpdf.com/examples/iia.php?id=263
내 목적을 위해, 나는 이미지의 벡터 특성 (래스터 화 없음)을 유지하면서 특정 크기와 위치에서 PDF로 그것을 그려야했습니다.
SAXSVGDocumentFactory.CreatesVGDocument () 함수에서 널리 퍼져있는 SVG 파일을 우회하고 싶었습니다. 플랫 파일 대신 SVG 텍스트 문자열을 사용하는 데 도움이되는 다음 게시물이 도움이되었습니다.
http://batik.2283329.n4.nabble.com/parse-svg-from-string-td3539080.html
문자열에서 stringReader를 생성하고 saxsvgdocumentFactory#createCument (String, Reader) 메소드로 전달해야합니다. 첫 번째 매개 변수로 문자열로 전달한 URI는 SVG 문서의 기본 문서 URI입니다. SVG가 외부 파일을 참조하는 경우에만 중요해야합니다.
친애하는,
다니엘
ITEXT 예제에서 파생 된 자바 소스 :
// SVG as a text string.
String svg = "<svg>...</svg>";
// Create the PDF document.
// rootPath is the present working directory path.
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(rootPath + "svg.pdf")));
document.open();
// Add paragraphs to the document...
document.add(new Paragraph("Paragraph 1"));
document.add(new Paragraph(" "));
// Boilerplate for drawing the SVG to the PDF.
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GVTBuilder builder = new GVTBuilder();
PdfContentByte cb = writer.getDirectContent();
// Parse the SVG and draw it to the PDF.
Graphics2D g2d = new PdfGraphics2D(cb, 725, 400);
SVGDocument chart = factory.createSVGDocument(rootPath, new StringReader(svg));
GraphicsNode chartGfx = builder.build(ctx, chart);
chartGfx.paint(g2d);
g2d.dispose();
// Add paragraphs to the document...
document.add(new Paragraph("Paragraph 2"));
document.add(new Paragraph(" "));
document.close();
이것은 당신이 작업중 인 PDF에 SVG를 그릴 것입니다. SVG는 텍스트 위의 플로팅 레이어로 나타납니다. 나는 여전히 그것을 움직여/스케일링하고 텍스트와 함께 휴식을 취하기 위해 노력하고 있지만, 그것은 질문의 즉각적인 범위를 벗어나기를 바랍니다.
이것이 도움이되기를 바랍니다.
건배
편집 : 다음을 사용하여 SVG를 인라인 객체로 구현할 수있었습니다. 주석은 선은 포지셔닝을 확인하기 위해 빠른 테두리를 추가하기위한 것입니다.
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(XMLResourceDescriptor.getXMLParserClassName());
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GVTBuilder builder = new GVTBuilder();
SVGDocument svgDoc = factory.createSVGDocument(rootPath, new StringReader(svg));
PdfTemplate svgTempl = PdfTemplate.createTemplate(writer, Float.parseFloat(svgDoc.getDocumentElement().getAttribute("width")), Float.parseFloat(svgDoc.getDocumentElement().getAttribute("height")));
Graphics2D g2d = new PdfGraphics2D(svgTempl, svgTempl.getWidth(), svgTempl.getHeight());
GraphicsNode chartGfx = builder.build(ctx, svgDoc);
chartGfx.paint(g2d);
g2d.dispose();
Image svgImg = new ImgTemplate(svgTempl);
svgImg.setAlignment(Image.ALIGN_CENTER);
//svgImg.setBorder(Image.BOX);
//svgImg.setBorderColor(new BaseColor(0xff, 0x00, 0x00));
//svgImg.setBorderWidth(1);
document.add(svgImg);
최근에 그래픽 2D 객체를 itext로 직접 보낼 수 있다는 것을 알게되었으며 결과 PDF 파일은 확장 가능한 벡터 그래픽만큼 우수합니다. 게시물에서 문제가 해결 될 수 있습니다.
Document document = new Document(PageSize.LETTER);
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(your file name));
} catch (Exception e) {
// do something with exception
}
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
// Create your graphics here - draw on the g2 Graphics object
g2.dispose();
cb.addTemplate(tp, 0, 100); // 0, 100 = x,y positioning of graphics in PDF page
document.close();
이것은 ITEXT 7.1.3을 사용하여 SVGConverter의 SVG 이미지를 렌더링했습니다.
PdfWriter writer = new PdfWriter(new FileOutputStream("/home/users/Documents/pdf/new.pdf"));
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
URL svgUrl = new File(svg).toURI().toURL();
doc.add(new Paragraph("new pikachu"));
Image image = SvgConverter.convertToImage(svgUrl.openStream(), pdfDoc);
doc.add(image);
doc.close();
ITEXT의 새로운 버전은 SVG 파일도 지원하고 있습니다. 참조하십시오 이것 페이지.