现在有很多网页页面转换成PDF文档的支持项目,我使用的是pd4ml;一个支持.net和java语言的项目。
这是主页:http://pd4ml.com/ . 有免费版和收费版,看了看免费版,感觉还不错,文档也比较详细。
web应用中需要添加pd4ml.jar和ss_css2,jar;
贴个例子:
ServletContext app;
protected Dimension format = PD4Constants.A4;
protected boolean landscapeValue = false;
protected int topValue = 10;
protected int leftValue = 10;
protected int rightValue = 10;
protected int bottomValue = 10;
protected String unitsValue = "mm";
protected String proxyHost = "";
protected int proxyPort = 0;
protected int userSpaceWidth = 780;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String httpurl = request.getParameter("httpurl");
// String urlstring = "http://localhost:8080/Itinerary/ProcessPOIs.jsp";
ItineraryWebSession iws = (ItineraryWebSession) request.getSession().getAttribute("iws");
if (iws != null && request.getSession().getAttribute("email") != null)
{
String email = (String) request.getSession().getAttribute("email");
app.setAttribute("iws_" + email, iws);
httpurl = httpurl + "?pdf=true&email=" + email;
// request.getSession().setAttribute("iws", iws);
}
try
{
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String("result".getBytes(), "8859_1"));
// response.addHeader("Content-Length", "" + file.length());
BufferedOutputStream output = null;
try
{
output = new BufferedOutputStream(response.getOutputStream());
this.runConverter(httpurl, output);
response.flushBuffer();
} catch (Exception e)
{
e.printStackTrace();
} finally
{
if (output != null)
output.close();
}
} catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
}
public void runConverter(String urlstring, BufferedOutputStream output) throws IOException
{
if (urlstring.length() > 0)
{
if (!urlstring.startsWith("http://") && !urlstring.startsWith("file:"))
{
urlstring = "http://" + urlstring;
}
if (proxyHost != null && proxyHost.length() != 0 && proxyPort != 0)
{
System.getProperties().setProperty("proxySet", "true");
System.getProperties().setProperty("proxyHost", proxyHost);
System.getProperties().setProperty("proxyPort", "" + proxyPort);
}
PD4ML pd4ml = new PD4ML();
try
{
pd4ml.setPageSize(landscapeValue ? pd4ml.changePageOrientation(format) : format);
} catch (Exception e)
{
e.printStackTrace();
}
if (unitsValue.equals("mm"))
{
pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));
} else
{
pd4ml.setPageInsets(new Insets(topValue, leftValue, bottomValue, rightValue));
}
pd4ml.setHtmlWidth(userSpaceWidth);
pd4ml.render(urlstring, output);
}
}
我在一个servlet中使用的时候,通过url新建的访问链接,发现session无法和浏览器中的共享,无奈把一部分数据放到了application中,访问完了之后再删掉。 当然,这只是pd4ml的应用方式之一,感兴趣的朋友可以深入研究一下。