使用spring MVC框架实现PDF的打印
import java.io.ByteArrayOutputStream;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
.util.PDFUtil;
.StringUtil;
public class PdfController
{
private static final String FONT_PATH = "C:/Windows/Fonts/SIMFANG.TTF";
@RequestMapping(value = "{fileName}.pdf", method =
{ RequestMethod.POST })
public void printPDF(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response)
throws IOException, Exception
{
String strFormId = request.getParameter("formId");
int formId = 0;
if (StringUtil.isNotEmpty(strFormId))
{
formId = Integer.parseInt(strFormId);
}
Map<String, String[]> paramMap = request.getParameterMap();
Map<String, String> map = new HashMap<String, String>();
for (String key : paramMap.keySet())
{
String[] value = paramMap.get(key);
if (value.length == 1)
{
map.put(key, value[0]);
}
else if (value.length > 1)
{
for (int i = 0; i < value.length; i++)
{
map.put(key + i, value[i]);
}
}
}
String docPath =路径
ByteArrayOutputStream baos = PDFUtil.generatePDF(docPath, FONT_PATH, map);
response.reset();
response.setContentType("application/pdf");
response.setContentLength(baos.size());
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
baos.close();
}
封装的PDF类
public class PDFUtil
{
public static ByteArrayOutputStream generatePDF(String pdfPath, String fontPath, Map<String, String> map)
throws IOException, DocumentException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(pdfPath);
PdfStamper stamper = new PdfStamper(reader, baos);
BaseFont font = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
AcroFields form = stamper.getAcroFields();
for (String key : map.keySet())
{
form.setFieldProperty(key, "textfont", font, null);
form.setField(key, map.get(key));
}
stamper.close();
return baos;
}
}