第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Apache FOP - 有沒有辦法以編程方式嵌入字體?

Apache FOP - 有沒有辦法以編程方式嵌入字體?

qq_笑_17 2022-07-06 17:02:20
使用 Apache FOP 創(chuàng)建 PDF 時,可以在配置文件中嵌入字體。當應用程序是 Web 應用程序并且需要在 WAR 文件中嵌入字體(因此被視為資源)時,就會出現(xiàn)問題。使用特定容器的文件夾結(jié)構(gòu)來確定戰(zhàn)爭的確切位置是不可接受的(在配置 xml 文件中,我們將 tag 設(shè)置為./,它被設(shè)置為運行容器的基本文件夾,如C:\Tomcat\bin)。所以問題是:有人知道以編程方式嵌入字體的方法嗎?
查看完整描述

3 回答

?
溫溫醬

TA貢獻1752條經(jīng)驗 獲得超4個贊

在經(jīng)歷了很多 FOP java 代碼之后,我設(shè)法讓它工作。


描述性版本

主要思想是強制 FOP 使用自定義PDFRendererConfigurator,在執(zhí)行時將返回所需的字體列表getCustomFontCollection()。


為了做到這一點,我們需要創(chuàng)建自定義PDFDocumentHandlerMaker,它將返回自定義PDFDocumentHandler(表單方法makeIFDocumentHandler()),然后返回我們的自定義PDFRendererConfigurator(來自getConfigurator()方法),如上所述,將設(shè)置自定義字體列表。


然后只需添加自定義PDFDocumentHandlerMaker即可RendererFactory。


FopFactory > RendererFactory > PDFDocumentHandlerMaker > PDFDocumentHandler > PDFRendererConfigurator


完整代碼

FopTest.java


public class FopTest {


    public static void main(String[] args) throws Exception {


        // the XSL FO file

        StreamSource xsltFile = new StreamSource(

                Thread.currentThread().getContextClassLoader().getResourceAsStream("template.xsl"));

        // the XML file which provides the input

        StreamSource xmlSource = new StreamSource(

                Thread.currentThread().getContextClassLoader().getResourceAsStream("employees.xml"));

        // create an instance of fop factory

        FopFactory fopFactory = new FopFactoryBuilder(new File(".").toURI()).build();


        RendererFactory rendererFactory = fopFactory.getRendererFactory();

        rendererFactory.addDocumentHandlerMaker(new CustomPDFDocumentHandlerMaker());


        // a user agent is needed for transformation

        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();


        // Setup output

        OutputStream out;

        out = new java.io.FileOutputStream("employee.pdf");


        try {

            // Construct fop with desired output format

            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);


            // Setup XSLT

            TransformerFactory factory = TransformerFactory.newInstance();

            Transformer transformer = factory.newTransformer(xsltFile);


            // Resulting SAX events (the generated FO) must be piped through to

            // FOP

            Result res = new SAXResult(fop.getDefaultHandler());


            // Start XSLT transformation and FOP processing

            // That's where the XML is first transformed to XSL-FO and then

            // PDF is created

            transformer.transform(xmlSource, res);

        } finally {

            out.close();

        }


    }


}

CustomPDFDocumentHandlerMaker.java


public class CustomPDFDocumentHandlerMaker extends PDFDocumentHandlerMaker {


    @Override

    public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) {

        CustomPDFDocumentHandler handler = new CustomPDFDocumentHandler(ifContext);

        FOUserAgent ua = ifContext.getUserAgent();

        if (ua.isAccessibilityEnabled()) {

            ua.setStructureTreeEventHandler(handler.getStructureTreeEventHandler());

        }

        return handler;

    }


}

CustomPDFDocumentHandler.java


public class CustomPDFDocumentHandler extends PDFDocumentHandler {


    public CustomPDFDocumentHandler(IFContext context) {

        super(context);

    }


    @Override

    public IFDocumentHandlerConfigurator getConfigurator() {

        return new CustomPDFRendererConfigurator(getUserAgent(), new PDFRendererConfigParser());

    }


}

CustomPDFRendererConfigurator.java


public class CustomPDFRendererConfigurator extends PDFRendererConfigurator {


    public CustomPDFRendererConfigurator(FOUserAgent userAgent, RendererConfigParser rendererConfigParser) {

        super(userAgent, rendererConfigParser);

    }


    @Override

    protected FontCollection getCustomFontCollection(InternalResourceResolver resolver, String mimeType)

            throws FOPException {


        List<EmbedFontInfo> fontList = new ArrayList<EmbedFontInfo>();

        try {

            FontUris fontUris = new FontUris(Thread.currentThread().getContextClassLoader().getResource("UbuntuMono-Bold.ttf").toURI(), null);

            List<FontTriplet> triplets = new ArrayList<FontTriplet>();

            triplets.add(new FontTriplet("UbuntuMono", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL));

            EmbedFontInfo fontInfo = new EmbedFontInfo(fontUris, false, false, triplets, null, EncodingMode.AUTO, EmbeddingMode.AUTO);

            fontList.add(fontInfo);

        } catch (Exception e) {

            e.printStackTrace();

        }


        return createCollectionFromFontList(resolver, fontList);

    }


}


查看完整回答
反對 回復 2022-07-06
?
瀟瀟雨雨

TA貢獻1833條經(jīng)驗 獲得超4個贊

是的,你可以這樣做。您需要以編程方式設(shè)置 FOP 的第一個基本目錄。


    fopFactory = FopFactory.newInstance();

    // for image base URL : images from Resource path of project

    String serverPath = request.getSession().getServletContext().getRealPath("/");

    fopFactory.setBaseURL(serverPath);

    // for fonts base URL :  .ttf from Resource path of project

    fopFactory.getFontManager().setFontBaseURL(serverPath);

然后使用 FOB 字體配置文件。它將使用上面的基本路徑。


只需將您的字體文件放在 Web 應用程序資源文件夾中,并在 FOP 的字體配置文件中引用該路徑。


評論后:以編程方式讀取字體配置(仍按要求不是首選和干凈的方式)


    //This is NON tested and PSEUDO code to get understanding of logic

    FontUris fontUris = new FontUris(new URI("<font.ttf relative path>"), null);

    EmbedFontInfo fontInfo = new EmbedFontInfo(fontUris, "is kerning enabled boolean", "is aldvaned enabled boolean", null, "subFontName");

    List<EmbedFontInfo> fontInfoList = new ArrayList<>();

    fontInfoList.add(fontInfo);

    //set base URL for Font Manager to use relative path of ttf file.

    fopFactory.getFontManager().updateReferencedFonts(fontInfoList);

您可以獲得有關(guān) FOP 相對路徑的更多信息https://xmlgraphics.apache.org/fop/2.2/configuration.html


查看完整回答
反對 回復 2022-07-06
?
慕雪6442864

TA貢獻1812條經(jīng)驗 獲得超5個贊

以下方法可能對那些使用PDFTranscoder.


將以下xml模板放入資源中:


<?xml version="1.0" encoding="UTF-8"?>

<fop version="1.0">

   <fonts>

       <font kerning="no" embed-url="IBM_PLEX_MONO_PATH" embedding-mode="subset">

               <font-triplet name="IBM Plex Mono" style="normal" weight="normal"/>

      </font>

   </fonts>

</fop>

然后可以加載此 xml 并IBM_PLEX_MONO_PATH在運行時將帶有字體 () 的行替換為資源包中字體的實際 URI:


private val fopConfig = DefaultConfigurationBuilder()

    .buildFromFile(javaClass.getResourceAsStream("/fonts/fopconf.xml")?.use {

        val xml = BufferedReader(InputStreamReader(it)).use { bf ->

            bf.readLines()

                .joinToString("")

                .replace(

                    "IBM_PLEX_MONO_PATH",

                    javaClass.getResource("/fonts/IBM_Plex_Mono/IBMPlexMono-Text.ttf")!!.toURI().toString()

                )

        }

        val file = Files.createTempFile("fopconf", "xml")

        file.writeText(xml)

        file.toFile()

    })

現(xiàn)在可以使用此配置,PDFTranscoder您的自定義字體可能會被渲染并嵌入到 PDF 中:


 val pdfTranscoder = if (type == PDF) PDFTranscoder() else EPSTranscoder()

    ContainerUtil.configure(pdfTranscoder, fopConfig)

    val input = TranscoderInput(ByteArrayInputStream(svg.toByteArray()))

    ByteArrayOutputStream().use { byteArrayOutputStream ->

        val output = TranscoderOutput(byteArrayOutputStream)

        pdfTranscoder.transcode(input, output)

        byteArrayOutputStream.toByteArray()

    }


查看完整回答
反對 回復 2022-07-06
  • 3 回答
  • 0 關(guān)注
  • 381 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號