1.maven项目进入依赖

  <dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>core-renderer</artifactId>
<version>R8pre2</version>
</dependency> <dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.0.8</version>
</dependency> <dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.4</version>
</dependency>

2.将html页面进行封装

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ include file="../../../common.jsp" %>
<link rel="stylesheet" type="text/css" href="${basePath}css/bootstrap-table.css"/>
<link rel="stylesheet" type="text/css" href="${basePath}css/bootstrap.min.css"/>
<script type="text/javascript" src="${basePath}js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="${basePath}js/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript" src="<%=basePath %>js/jquery.PrintArea.js"></script>
<script src="${basePath}js/html2canvas/html2canvas.js"></script>
<script src="${basePath}js/html2canvas/jspdf.debug.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script> -->
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
.table{
border:1px solid #cad9ea;
color:#666;
margin-bottom: 10px;
margin-top: 10px;
}
.table th {
background-repeat:repeat-x;
height:30px;
}
.table td,.table th{
border:1px solid #cad9ea;
padding:0 0.5em 0;
}
.table tr.alter{
background-color:#f5fafe;
}
.imgStyle{
margin-bottom:0.5em;
width: 220px;
height: 150px;
}
textarea{
margin-bottom: 4px;
}
#stamp{
background-color: #008CBA; /* Green */
border: none;
color: white;
padding: 4px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 13px;
margin: 4px 2px;
cursor: pointer;
}
#picture{
position: absolute;
right: 200px;
top: 650px;
}
html{
height:60%
}
</style>
<style type="text/css" media="print">
.noprint { display:none;}
</style>
<script type="text/javascript">
$(document).ready(function(){ //通过AJAX后台取数据 //获取当前的时间
var day = new Date();
Year= day.getFullYear();//支持IE和火狐浏览器.
Month= day.getMonth()+1;
Day = day.getDate();
// $('#year').text(Year);
// $('#month').text(Month);
// $('#day').text(Day);
// $('#year2').text(Year);
// $('#month2').text(Month);
// $('#day2').text(Day); // var a=new Date(new Date());
// var year1=a.getFullYear();//年
// var month1=a.getMonth()+1;//月份(月份是从0~11,所以显示时要加1)
// // month1=month1<10?'0'+month1:month1;
// var day1=a.getDate();//日期
// // day1=day1<10?"0"+day1:day1;
// var str1=year1+'年'+month1+'月'+day1+'日';
// $('#year2').text(str1);
// $('#year').text(str1); //var driver_bespeak_id = ${requestScope.driver_bespeak_id};
//获取驾驶员预约号
// $.post(
// "getYuyueDataByAjax.action"
// ,{
// driver_bespeak_id : ${requestScope.driver_bespeak_id},
// }
// ,function(data){ // $("#username").text(data.username); // });
});
</script> <script type="text/javascript"> //页面格式改成页签的格式 var hkey_root,hkey_path,hkey_key;
hkey_root="HKEY_CURRENT_USER";
hkey_path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\"; $(document).ready(function(){ //后续操作
$("#stamp").click(function(){ debugger;
var printHtml = "<?xml version='1.0' encoding='UTF-8'?>";
printHtml += "<html xmlns='http://www.w3.org/1999/xhtml'>";
printHtml +="<head>";
printHtml +="<title>页面打印</title>";
printHtml +="<style media= 'print' >";
printHtml +=" @page{size: A4 portrait;};";/* 可以控制打印方向,portrait: 纵向打印, landscape: 横向。 */
printHtml +=" .page { page-break-after: always; } </style> ";
printHtml +=" </head> ";
printHtml +=" <body bgcolor='white' style='font-family:SimSun; height:100%;' screen_capture_injected='true' ryt11773='1'> ";
printHtml +=" <h4 style='font-size:30px;font-family:SimSun;text-align: center;'><b>3333333</b></h4>";
printHtml +=" <div style='padding-left:430px;'><img style='position:relative;width:200px;height:60px;' alt='' src='${basePath}/face/QRCode/${CarInfo.carId}.png'/></div>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 45px;'>车辆管理所:</h4> ";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 130px;'><span style='float:left;'>兹有津</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:120px;'> ${CarInfo.carNum} </span><span style='float:left;'>车辆所有人</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:200px;'><c:if test='${CarInfo.belongs==1}'> ${CarInfo.manCompany}</c:if><c:if test='${CarInfo.belongs==2}'> ${CarInfo.terrace}</c:if> <c:if test='${CarInfo.belongs==3}'> ${CarInfo.manCompany}</c:if></span></h4><br/>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 60px;margin-top:20px;'><span style='float:left;'>333</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:170px;'> ${CarInfo.labels}</span><span style='float:left;'> 33</span> <span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:207px;'> ${CarInfo.engineNum}</span></h4><br/>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 60px;margin-top:20px;'>33,33性质变更为“33”。</h4>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 60px;'><span style='float:left;'>333:</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:270px;'> 33。</span></h4>";
printHtml +=" <h4 style='font-size:20px;font-family:SimSun;padding-right:80px;'><span style='padding-left: 460px;'><span>(33)</span></span></h4>";
printHtml +=" <div style='padding-left:460px;margin-top:-70px;'><img style='position:relative;margin-top:-100px;' width='140px;' height='140px;' src='${basePath}images/stamp.png'/></div>";
printHtml +=" <h4 style='font-size:20px;font-family:SimSun;padding-right:80px;margin-top:-10px;'><span style='padding-left: 70px;'><span id='year'>${time }</span></span></h4>";
printHtml +=" <hr style='height:1px;border:none;border-top:1px dashed black;' /><br/>";
printHtml +=" <h4 style='font-size:30px;font-family:SimSun;text-align: center;'><b>33</b></h4>";
printHtml +=" <div style='padding-left:430px;'><img style='position:relative;width:200px;height:60px;' alt='' src='${basePath}/face/QRCode/${CarInfo.carId}.png'/></div>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 45px;'>33:</h4> ";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 130px;'><span style='float:left;'>33</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:120px;'> ${CarInfo.carNum} </span><span style='float:left;'>33</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:200px;'><c:if test='${CarInfo.belongs==1}'> ${CarInfo.manCompany}</c:if><c:if test='${CarInfo.belongs==2}'> ${CarInfo.terrace}</c:if> <c:if test='${CarInfo.belongs==3}'> ${CarInfo.manCompany}</c:if></span></h4><br/>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 60px;margin-top:20px;'><span style='float:left;'>33</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:170px;'> ${CarInfo.labels}</span><span style='float:left;'> 发动机号 </span> <span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:207px;'> ${CarInfo.engineNum}</span></h4><br/>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 60px;margin-top:20px;'>33,33性质变更为“33”。</h4>";
printHtml +=" <h4 style='font-size:22px;font-family:SimSun;padding-left: 60px;'><span style='float:left;'>备注:</span><span style='padding-bottom: 5px; border-bottom: 1px solid #000;float:left;display:block;width:270px;'> 3333。</span></h4>";
printHtml +=" <h4 style='font-size:20px;font-family:SimSun;padding-right:80px;'><span style='padding-left: 460px;'><span>(333)</span></span></h4>";
printHtml +=" <div style='padding-left:460px;margin-top:-70px;'><img style='position:relative;margin-top:-100px;' width='140px;' height='140px;' src='${basePath}images/stamp.png'/></div>";
printHtml +=" <h4 style='font-size:20px;font-family:SimSun;padding-right:80px;margin-top:-10px;'><span style='padding-left: 70px;'><span id='year'>${time }</span></span></h4>"; printHtml +=" </body>";
printHtml +="</html>";
var path = $("#path").val();
$.ajax({
type:"POST",
url:"downPdf.action",
data:{"printHtml":printHtml,"path":path},
success:function(data){
if(data == 1){
alert("下载成功");
}
}
}); });
});
function browseFolder(path) {
try {
var Message = "我的电脑"; //选择框提示信息
var Shell = new ActiveXObject("Shell.Application");
var Folder = Shell.BrowseForFolder(0, Message, 64, 17); //起始目录为:我的电脑
//var Folder = Shell.BrowseForFolder(0, Message, 0); //起始目录为:桌面
if (Folder != null) {
Folder = Folder.items(); // 返回 FolderItems 对象
Folder = Folder.item(); // 返回 Folderitem 对象
Folder = Folder.Path; // 返回路径
if (Folder.charAt(Folder.length - 1) != "\\") {
Folder = Folder + "\\";
}
document.getElementById(path).value = Folder;
return Folder;
}
}
catch (e) {
alert(e.message);
}
} function PageSetup_Null(){
try{
var RegWsh = new ActiveXObject("WScript.Shell") ;
hkey_key="header" ;
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"") ;
hkey_key="footer" ;
RegWsh.RegWrite(hkey_root+hkey_path+hkey_key,"") ;
}
catch(e){}
} </script> </head>
<body>
<div class="container" style="height:60%">
<div id="zhongxin" style="margin-left:10%"> <div style="padding-top:30px;"></div>
<div class="panel panel-default" id="part1" style="border:none;"> <!-- 第一部分 -->
<br> <div id="prin" class="noprint" style="margin-left:-400px">
<input id="path" type="text" name="path" size="30" style="float:right;" disabled="disabled">
<input type=button value="选择" onclick="browseFolder('path')" style="float:right;margin-right:-270px;">
<center><button id="stamp" class="noprint" style="float:right;margin-right:-370px;margin-top:-1px;" ><center>下载pdf</center></button></center>
</div> </body>
</html>

3.action

/**
* html下载pdf
* @param request
* @return
*/
@RequestMapping("/downPdf")
@ResponseBody
public int downPdf(HttpServletRequest request) {
try{
String printHtml = request.getParameter("printHtml");
String path = request.getParameter("path");
System.out.println("开始转换pdf");
PdfUtil.htmlToPdf(path+"content.pdf",printHtml);
return 1;
}catch (Exception e) {
System.out.println(e.getMessage());
return 2;
}
}

4.工具类

//导入的包
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer; import com.lowagie.text.pdf.BaseFont; public class PdfUtil { /**
* 把URL转换为PDF
*
* @param outputFile
* , 示例:/data/fs/inspector/BJ20150522001.pdf
* @param url
* ,示例:http :xxxx
* @return
* @throws Exception
*/
public static boolean htmlToPdf(String outputFile, String url)throws Exception {
File outFile = new File(outputFile);
if (!outFile.exists()) {
outFile.getParentFile().mkdirs();
} OutputStream os = new FileOutputStream(outputFile); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(url.getBytes("UTF-8"))); //Document document = new Document(PageSize.A4, 50, 50, 50, 50);
ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(doc, null); //renderer.setDocument(url);
String fontPath = PdfUtil.class.getClassLoader().getResource("").toString().replaceAll("file:/", "")+ "simsun.ttc";
System.out.println(fontPath); // 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(fontPath, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
os.flush();
os.close(); System.out.println("文件转换成功");
return true;
}
}

利用itext将html页面转成pdf(不模糊)的更多相关文章

  1. Microsoft.Office.Interop.Excel的用法以及利用Microsoft.Office.Interop.Excel将web页面转成PDF

    1.常见用法           using Microsoft.Office.Interop.Excel; 1)新建一个Excel ApplicationClass ExcelApp = New A ...

  2. 利用Microsoft.Office.Interop.Excel 将web页面转成PDF

    网上有很多将Web页面转成PDF的方法,还有许多收费的第三方插件.其实利用Office 自带的将EXCEL发布成PDF的功能就可以实现,如果你的需求没有多复杂,可以采用笔者的方法. 首先将web页面h ...

  3. 【jsPDF】jsPDF插件实现将html页面转换成PDF,并下载,支持分页

    1.目的:在前段是 jQuery库 或者 VUE库 或者两者混合库,将html 页面和数据 转换成PDF格式并下载,支持分页 1.项目背景: 对客户报修记录进行分类统计,并生成各种饼图.柱状图.线性图 ...

  4. 使用JavaScript将当前页面保存成PDF,支持图片和文字的保存

    前端开发的朋友们可能会遇到这个需求:将您负责开发的网页的全部内容,包括文字和图片,一起保存成一个PDF文件.如果采用屏幕截图的话,默认Windows操作系统的截图按钮无法完整截取超过一屏幕的屏幕内容. ...

  5. 利用WkHtmlToPdf,把H5 转成PDF

    工具下载地址: 链接:https://pan.baidu.com/s/1TSq2WWZcvPwuIfPRHST-FA 提取码:wkx8 原理: 通过IIS访问页面,利用WkHtmlToPdf.exe, ...

  6. html页面转换成pdf

    一般页面都是.jsp页面,所以要把.jsp转换成html,在生成pdf,在网上找了好多方法,只有用一个插件,wkhtmltopdf-0.8.3.exe,生成的pdf会相对的好看. 先附上我做的.jsp ...

  7. 利用FlashPaper在web页面中显示PDF文件(兼容各浏览器)

    应项目需求要把PDF内嵌到网页中显示,其中有了很多办法,比如用<embed/>元素放入PDF文件,但是效果不理想,浏览器兼容不理想,在ie9/8(其他版本没有测试)显示会提示下载pdf文件 ...

  8. vue将页面导出成pdf

    npm i jspdf-html2canvas prinOut(){ // 导出pdf let page = document.querySelector('.app-main'); // page ...

  9. Vue 页面导出成PDF文件

    注意事项 如果导出的页面中设计到图片或者其他文件跨域文件,需要后端服务配合 安装依赖 npm install html2Canvas --save npm install jspdf--save 封装 ...

随机推荐

  1. flask 电子邮件Flask-Mail

    电子邮件 在web程序中,经常会需要发送电子邮件.比如,在用户注册账户时发送确认邮件:定期向用户发送热门内容或是促销信息等等.在Web程序中发送电子邮件并不复杂,借助扩展Flask-Mail或是第三方 ...

  2. Comparing Spring AOP and AspectJ

    AOP 概念 在我们开始之前 , 让我们做一个快速.高级别审查的核心术语和概念 : 方面 — —标准 / 特征代码被分散在多个场所中的应用 , 通常不同于实际的业务逻辑 (例如 , 交易管理) .各方 ...

  3. vue:vuex中mapState、mapGetters、mapActions辅助函数及Module的使用

    一.普通store中使用mapState.mapGetters辅助函数: 在src目录下建立store文件夹: ​ index.js如下: import Vue from 'vue'; import ...

  4. 5.1JAVA基础复习——JAVA中的静态代码块、构造代码块、构造函数、局部代码块区别

    构造代码块: 在类中定义可以给所有对象进行初始化.局部代码块: 在方法中定义属性的生命周期.静态代码块: 在类中定义用于给类调用时属性的初始化 构造函数与构造代码块的区别: 构造函数是给对应的对象进行 ...

  5. JZ2440学习笔记之第一个裸机程序(Keil-MDK)

    CPU:S3C2440, ARM920T, Internal 4KB RAM, Support boot from NAND flash, 128MB for each bank. JZ2440:Me ...

  6. 依据word模板批量生成试卷

    java-word-MassProduction 目录 使用方法 开发流程 一.使用方法 1.制造题库所需Word模板 需要填充数据的地方使用 ${pid} 代替. 将这个word选择另存为,保存格式 ...

  7. day11函数的参数,函数对象 - 函数名,函数的嵌套调用

    复习 # 什么是函数:具体特定功能的代码块 - 特定功能代码块作为一个整体,并给该整体命名,就是函数 # 函数的优点: # 1.减少代码的冗余 # 2.结构清晰,可读性强 # 3.具有复用性,开发效率 ...

  8. 【Django试图与网址003】

    Django中网址是写在 urls.py 文件中,用正则表达式对应 views.py 中的一个函数(或者generic类),我们用一个项目来演示. 一,首先,新建一个项目(project), 名称为 ...

  9. Servlet和Filter的区别

    1.Filter是一个接口,而Servlet是一个类继承于Httpservlet 2.生命周期的不同,Filter在Web App被加载时,创建该Filter的实例,并调用init()方法(仅创建一个 ...

  10. windows服务加定时器实现

    首先在项目中添加windows服务 然后双击“MainService.cs”,在上面点右键“打开代码” 以下是我的实例代码 partial class MainService : ServiceBas ...