有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用嵌入式字体调用Graphics2D。抽绳(…)使用iText(DefaultFontMapper?)

要生成有效的PDF/X文档,必须嵌入所有字体。不知何故,我不可能在Graphics2D环境中使用这些字体

此Unittests显示了问题(注释行是我进行的一些测试):

import java.awt.Font;
import java.awt.Graphics2D;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Map.Entry;

import org.junit.Test;

import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.awt.DefaultFontMapper.BaseFontParameters;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;

public class TestFont
{

    @Test
    public void shouldBeAbleToAddFountsAndDrawOnCanvas() throws FileNotFoundException, DocumentException
    {
        final DefaultFontMapper mapper = new DefaultFontMapper();
        mapper.insertDirectory(".");

        final PrintStream out2 = new PrintStream(System.out);
        for (final Entry<String, BaseFontParameters> entry : mapper.getMapper().entrySet())
        {
            out2.println(String.format("%s: %s", entry.getKey(), entry.getValue().fontName));
        }
        out2.flush();

        final float width = 150;
        final float height = 150;

        final Document document = new Document(new Rectangle(width, height));
        final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("fonts.pdf"));
        writer.setPDFXConformance(PdfWriter.PDFX32002);

        document.open();
        final Graphics2D g2d = new PdfGraphics2D(writer.getDirectContent(), width, height, mapper);

        g2d.setFont(new Font("Comicate", Font.PLAIN, 12));

        g2d.drawString("Hello world", 5, 24);

        g2d.dispose();

        document.close();
    }

}

它将抛出一个带有消息的PdfXConformanceException:“所有字体都必须嵌入。这个不是:Helvetica

我已经浏览了PdfGraphics2D类来检查setFont()实现,发现将使用FontMapper。我已经在上面的单元测试中添加了这个

public void setFont(Font f) {
    if (f == null)
        return;
    if (onlyShapes) {
        font = f;
        return;
    }
    if (f == font)
        return;
    font = f;
    fontSize = f.getSize2D();
    baseFont = getCachedBaseFont(f);
}

private BaseFont getCachedBaseFont(Font f) {
    synchronized (baseFonts) {
        BaseFont bf = (BaseFont)baseFonts.get(f.getFontName());
        if (bf == null) {
            bf = fontMapper.awtToPdf(f);
            baseFonts.put(f.getFontName(), bf);
        }
        return bf;
    }
}

Unittest基于iText-in-Action手册中的this exampleHere是有关FontMapper的其他一些示例

要运行Unittest,您需要此依赖项:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.3.2</version>
</dependency>

自定义字体(位于“.”中)你会发现here

控制台输出向我显示以下内容(以标识fontName):

Comicate: ./COMICATE.TTF

共 (2) 个答案

  1. # 1 楼答案

    通过定义新的BaseFont并实现FontMapper()的接口>&燃气轮机&燃气轮机;public BaseFont awtToPdf(java.awt.Font)。这将应用awt。嵌入到pdf中的字体

    在下面的示例中,我“print”g2D(包括“drawString”方法),在外部类中绘制。结果仅导出带有嵌入式“ArialMT”和“Arial BoldMT”字体的矢量pdf

    preview img

        PdfWriter pdfWriter = null;
        try {
            pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            BaseFont fontRegular = BaseFont.createFont("C:\\Windows\\Fonts\\arial_0.ttf", "Cp1251", BaseFont.EMBEDDED);
            BaseFont fontBold = BaseFont.createFont("C:\\Windows\\Fonts\\arialbd_0.ttf", "Cp1251", BaseFont.EMBEDDED);
            FontMapper fontMapper = new FontMapper() {
    
                @Override
                public java.awt.Font pdfToAwt(BaseFont arg0, int arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
    
                @Override
                public BaseFont awtToPdf(java.awt.Font font) {
                    if (font.equals(Fonts.getFontRegular10()) || font.equals(Fonts.getFontRegular12())){
                        return fontRegular;
                    }
                    else {
                        return fontBold;
                    }
                }
            };
            PdfContentByte cb = pdfWriter.getDirectContent();
            PdfTemplate template = cb.createTemplate(MainFrame.getFRAME_WIDTH(), MainFrame.getFRAME_HEIGHT());
            Graphics2D g2D = new PdfGraphics2D(template, MainFrame.getFRAME_WIDTH(), MainFrame.getFRAME_HEIGHT(), fontMapper);
            MainFrame.getPanel().print(g2D);
            g2D.dispose();
            cb.addTemplate(template, 0, 0);
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        finally {
            document.close();
        }
    
  2. # 2 楼答案

    我不确定纠正代码中错误的确切方法,但有一些简单的解决方法:

    解决方法1)创建一个BuffereImage来执行所有图形绘制。然后,您可以使用所有正常的java.awt.Graphics函数,如drawStringsetColor,而不考虑iText,完成后只需将图像绘制到PDF。警告:缩放时文本质量不高,但以下是一个示例:

    //create doccument and writer    
    Rectangle pagesize = new Rectangle(200, 100);
    Document document= new Document(pagesize);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\sample.pdf"));
    
    BufferedImage bf = new BufferedImage(BorderWidth, BorderHeight, BorderWidth);
    //Do all graphics code here, draw strings and images etc
        //Some code to set font (java.awt.Font)
        //Some code to draw string
        //Some code to draw image?
    
    //Convert BufferedImage to Image
    Image img = (Image)bf;
    //draw image to PDF using writer
    writer.getDirectContentUnder().addImage(img);
    

    解决方法2)这使用iText功能绘制字符串,无需创建任何图形对象,字体通过使用BaseFont处理,如下所示:

    //create doccument and writer    
    Rectangle pagesize = new Rectangle(200, 100);
    Document document= new Document(pagesize);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\sample.pdf"));
    
    document.open();
    //This sample uses the "GOTHIC.TTF" font file located in the "Template" package
    BaseFont bf = BaseFont.createFont(GUI.class.getClass().getResource("/Template/GOTHIC.TTF") + "", BaseFont.WINANSI, BaseFont.EMBEDDED);
    
    //set font type, size and color
    Font font = new Font(bf, 13.5f);
    
    PdfContentByte canvas = writer.getDirectContent();
    
    canvas.beginText();
    canvas.setFontAndSize(bf, 10);
    //Method Usage: showTextAligned(Align, String, x, y, rotation);
    canvas.showTextAligned(Element.ALIGN_TOP, "My Text Here", 75, 40, 0);
    canvas.endText();
    
    document.close();
    

    我知道这并没有给出你想要的答案,但是如果你只是画了一小段文字,那么变通方法2很好,我以前使用过类似于变通方法2的东西。如果这没有帮助,那么我相信布鲁诺会有答案的