在JSF中加载没有ServletContext的字体[无法识别字体类型。]

时间:2018-12-17 09:41:33

标签: servlets itext

我正在研究JSF / Primefaces项目。

我创建了一个后台任务工作,该任务为可运行的类加注星标以创建PDF。 我们正在使用iText 7创建PDF。 现在,我需要更改默认字体,并使用ServletContext来获取路径。

只要通过用户交互启动作业,我的ServletContext解决方案就可以使用,但是如果从调度程序中启动了作业,则无法使用。

背景调度程序

package com.myproject.myproject.core.util;

import com.myproject.myproject.reports.ReportController;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;


@WebListener
public class BackgroundJobManager implements ServletContextListener {

    private static ScheduledExecutorService scheduler;

    private static final Integer DEFAULT_HOUR = 12;
    private static final Integer DEFAULT_MINUTE = 30;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        try {
            startSchedule();
        } catch (Exception ex) {
            System.err.println("e: " + ex.getMessage());
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

    public static void startSchedule() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule(new EmergencyReportingController(), getNextScheduleDelay(), TimeUnit.MILLISECONDS);
    }

    private static Long getNextScheduleDelay() {

        nextDate.add(Calendar.DATE, 1);
        nextDate.set(Calendar.HOUR_OF_DAY, DEFAULT_HOUR);
        nextDate.set(Calendar.MINUTE, DEFAULT_MINUTE);
        nextDate.set(Calendar.SECOND, 0);
        nextDate.set(Calendar.MILLISECOND, 0);
        nextDate.set(Calendar.AM_PM, nextDate.get(Calendar.AM_PM));

        Long delay = nextDate.getTime().getTime() - now.getTime().getTime();

        return delay;
    }
}

可运行类

package com.myproject.myproject.reports;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

@ManagedBean(eager = true)
@ApplicationScoped

public class ReportController implements Runnable {

    private static final long serialVersionUID = 1L;

    private String CALIBRI_FONT = "";
    private PdfFont FONT = null;

    @Override
    public void run() {
        try {
            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
            CALIBRI_FONT = servletContext.getRealPath("/resources/fonts/calibri.ttf");
            FONT = PdfFontFactory.createFont(CALIBRI_FONT);
        } catch (Exception e) {
            System.out.println("exem: " + e.getMessage());
        }
    }
}

我收到此错误

  

无法识别字体类型。

enter image description here

0 个答案:

没有答案