我创建了一个 servlet 来处理将 JSP 中显示的 JFreeChart 保存到 PDF 文件。到目前为止我使用的代码是:
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.JFreeChart;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
public class ChartPrintServlet extends HttpServlet {
private static final long serialVersionUID = -2445101551756014281L;
protected void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
JFreeChart jFreeChart = (JFreeChart) request.getSession().getAttribute("jFreeChart");
String url = "";
int height = 1024;
int width = 1152;
if (jFreeChart == null)
{
url = "/do/error";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
else
{
AbsencesGanttChartPostProcessor postProc = new AbsencesGanttChartPostProcessor();
postProc.processChart(jFreeChart, null);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"absences.pdf\"");
OutputStream out = response.getOutputStream();
try
{
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize.rotate(), 30, 30, 30, 30);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(height, width);
Graphics2D g2 = tp.createGraphics(height, width, new DefaultFontMapper());
Rectangle2D r2D = new Rectangle2D.Double(0, 0, height, width);
jFreeChart.draw(g2, r2D);
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
catch (DocumentException de)
{
System.err.println(de.getMessage());
}
finally
{
out.close();
}
}
}
protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
}
我已经在各处交换了高度和宽度,以使 PDF 看起来不错,但我真正想要的是能够像在横向模式下一样创建 PDF。
如果我尝试
Graphics2D g2 = tp.createGraphics(height, width, new DefaultFontMapper());
g2.rotate(90)
然后 PDF 只打印一个白色的空白页。
创建 PDF 时,使用 itext / Java awt API 旋转整个文档(包括下面的 JFreeChart)的正确方法是什么?