سؤال

نحن نستخدم iText لإنشاء ملفات PDF من Java (استنادًا جزئيًا إلى التوصيات الموجودة على هذا الموقع).ومع ذلك، فإن تضمين نسخة من شعارنا بتنسيق صورة مثل GIF يؤدي إلى ظهوره غريبًا بعض الشيء عندما يقوم الأشخاص بالتكبير والتصغير.

من الناحية المثالية، نرغب في تضمين الصورة بتنسيق متجه، مثل EPS أو SVG أو قالب PDF فقط.يدعي موقع الويب أنه تم إسقاط دعم EPS، وأن تضمين ملف PDF أو PS داخل ملف PDF يمكن أن يؤدي إلى حدوث أخطاء، ولا يذكر حتى SVG.

يستخدم الكود الخاص بنا واجهة برمجة تطبيقات Graphics2D بدلاً من iText مباشرةً، ولكننا سنكون على استعداد للخروج من وضع AWT واستخدام iText نفسه إذا حقق النتيجة.كيف يمكن القيام بذلك؟

هل كانت مفيدة؟

المحلول

ووفقا لhref="http://itextdocs.lowagie.com/tutorial/objects/images/index.php" الوثائق rel="noreferrer"> iText يدعم صيغ الصور التالية: JPEG ، GIF، PNG، TIFF، BMP، WMF وEPS. أنا لا أعرف إذا كان هذا قد يكون من أي مساعدة ولكن لقد استخدمت بنجاح iTextSharp لتضمين ناقلات <أ href ل = "http://en.wikipedia.org/wiki/Windows_Metafile" يختلط = "noreferrer"> WMF صورة في ملف PDF:

وC #:

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);
}

ويمكن أن تضاف المثال صورة بسهولة إلى قوات الدفاع الشعبي (في حالتي كتوقيع).

لقد وجدت بضعة أمثلة من مؤلف iText تستخدم واجهة برمجة تطبيقات Graphics2D ومكتبة Apache Batik لرسم SVG في ملف PDF.

http://itextpdf.com/examples/iia.php?id=269

http://itextpdf.com/examples/iia.php?id=263

لأغراضي، كنت بحاجة إلى أخذ سلسلة من ملفات SVG ورسمها في ملف PDF بحجم وموقع معينين مع الحفاظ على الطبيعة المتجهة للصورة (بدون تنقيط).

أردت تجاوز ملف SVG الذي يبدو سائدًا في وظائف SAXSVGDocumentFactory.createSVGDocument().لقد وجدت المنشور التالي مفيدًا لاستخدام سلسلة نصية SVG بدلاً من الملف الثابت.

http://batik.2283329.n4.nabble.com/Parse-SVG-from-String-td3539080.html

يجب عليك إنشاء StringReader من السلسلة الخاصة بك وتمرير ذلك إلى طريقة SAXSVGDocumentFactory#createDocument(String, Reader).سيكون عنوان URI الذي تمرره كمعلمة أولى كسلسلة هو URI للمستند الأساسي لمستند SVG.يجب أن يكون هذا مهمًا فقط إذا كان ملف SVG الخاص بك يشير إلى أي ملفات خارجية.

أطيب التحيات،

دانيال

مصدر Java مشتق من أمثلة 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();

لاحظ أن هذا سيؤدي إلى رسم SVG إلى ملف PDF الذي تعمل عليه.يظهر 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);

وعلمت مؤخرا أنه يمكنك إرسال يعترض Graphics2D مباشرة إلى 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 لتقديم صورة SVG التي كتبها SVGConverter.

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 أيضا. يرجى الرجوع إلى هذه الصفحة .

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top