SpringBoot+Layui 打印PDF

1、下载C_Lodop打印插件
下载插件官网:http://www.lodop.net/

2、pom.xml添加依赖

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.9</version>
		</dependency>

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
		    <version>5.2.0</version>
		</dependency>

3、controller层
该代码是生成了一个表格,把页面传过去的参数通过findByForeach()方法找出来,用for循环叠加表格的行数。

@RequestMapping("/scorePDF")
	public Object scorePDF (@RequestParam("nums") Object nums, HttpServletResponse response) throws Exception {
		String datas = nums.toString();
		String[] str = datas.split(",");
		List<String> data = new ArrayList<String>();
		for (int i = 0; i < str.length; i++) {
			data.add(str[i]);
		}

		//用于存储listScore的每个for循环的值
		List list = new ArrayList<>();
		//查找选中的成绩信息
		List<StuExt> listScore = stuService.findByForeach(data);
		for (StuExt ext : listScore) {
			String[] arr = {ext.getStuno(),ext.getName(),ext.getCoursename(),String.valueOf(ext.getScore()),ext.getType()};
			list.add(arr);
		}

		try {
			Document document = new Document(PageSize.A4.rotate());
			File f = File.createTempFile("我的成绩单", ".pdf");
			PdfWriter.getInstance(document, new FileOutputStream(f));

			// 设置字体
			BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
					BaseFont.NOT_EMBEDDED);
			com.itextpdf.text.Font thFont =
					new com.itextpdf.text.Font(bfChinese, 22, com.itextpdf.text.Font.BOLD);
			com.itextpdf.text.Font nomalFont = new com.itextpdf.text.Font(bfChinese, 20,
					com.itextpdf.text.Font.NORMAL);


			document.open();

			// table1
			PdfPTable table1 = new PdfPTable(5);
			String[] ths = {"学号", "姓名", "课程", "成绩", "类型"};
			for (int i = 0; i < ths.length; i++) {
				Paragraph para = new Paragraph(ths[i], thFont);
				para.setAlignment(Element.ALIGN_CENTER);
				PdfPCell cell = new PdfPCell(para);
				cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				table1.addCell(cell);
			}
			document.add(table1);

			// table2

			for (int i = 0; i < list.size(); i++) {
				PdfPTable table2 = new PdfPTable(5);
				String[] arr = (String[]) list.get(i);
				for (int j = 0; j < arr.length; j++) {
					Paragraph para = new Paragraph(arr[j], nomalFont);
					para.setAlignment(Element.ALIGN_CENTER);
					PdfPCell cell = new PdfPCell(para);
					cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
					cell.setHorizontalAlignment(Element.ALIGN_CENTER);
					table2.addCell(cell);
				}
				document.add(table2);
			}

			document.close();

			PdfReader reader = new PdfReader(f.getAbsolutePath());

			StringBuffer script = new StringBuffer();
			script.append("this.print({bUI: false,bSilent: true,bShrinkToFit: false});")
					.append("\r\nthis.closeDoc();");

			ByteArrayOutputStream bos = new ByteArrayOutputStream();

			try {
				PdfStamper stamp = new PdfStamper(reader, bos);
				stamp.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar
						| PdfWriter.HideWindowUI);
				stamp.addJavaScript(script.toString());
				stamp.close();
			} catch (DocumentException e) {
			}
			response.getOutputStream().write(bos.toByteArray());
			return null;

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;

	}

4、页面

<button type="button" class="layui-btn layui-btn-primary" onclick="scorePDF()">打印成绩单</button>
function scorePDF (argument) {
    layui.use('table',function(){
      var table = layui.table
      var checkStatus = table.checkStatus('csInfo');
      var frame = document.createElement("IFRAME");
      if(checkStatus.data.length==0){
        parent.layer.msg('请先选择要打印的数据行!', {icon: 2});
        return ;
      }
      var nums = "";
      for(var i=0;i<checkStatus.data.length;i++){
        nums += checkStatus.data[i].id+",";
      }
      parent.layer.msg('打印中...', {icon: 16,shade: 0.3,time:5000});

      frame.style.display ="none";
      frame.src = "scorePDF?nums="+nums;//controller层的url
      document.body.appendChild(frame);
      frame.contentWindow.focus();
      frame.contentWindow.print();
    });
 }

5、打印结果可保存为PDF文件,也可连接打印机打印
SpringBoot+Layui 打印PDF_第1张图片
注意事项:
1、关于iText生成PDF文件,这个PDF文件的内容可以自己随心所欲,可以在网上找一些资料,我里面所描述的是一个表格,还可以生成段落等等。
2、代码中有需要的类可以找我,本人qq(2253978324),要备注好。
3、要是代码有什么写的不好,欢迎评论区评论。

你可能感兴趣的:(SpringBoot+Layui 打印PDF)