精华内容
下载资源
问答
  • javahtml转pdf
    千次阅读
    2017-06-13 15:02:07

    网上关于 html生产pdf的java代码许多,我就不说了。主要是记录一下乱码问题的关键
    1、html文件必须是utf-8编码格式的文件。
    2、代码中的获取方式也是utf-8的格式。
    3、其他的按照别人的教程编写

    更多相关内容
  • java html转pdf

    2021-05-06 16:24:37
    java html转pdf,pd4ml-370fx2pro.jar
  • JAVA HTML PDF

    千次阅读 2022-04-25 08:49:33
    JAVA 通过 itext,wkhtmltopdf 等,将 HTML PDF。 这里通过 wkhtmltopdf 实现htmlHTML转PDF wkhtmltopdf 是一个开源的,使用Qt WebKit 渲染引擎,把 html 转换为 pdf 文件的命令行工具。 wkhtmltopdf官网...

    JAVA 通过 itext,wkhtmltopdf 等,将 HTML 转成 PDF。
    这里通过 wkhtmltopdf 实现HTML转PDF

    wkhtmltopdf 是一个开源的,使用Qt WebKit 渲染引擎,把 html 转换为 pdf 文件的命令行工具。

    wkhtmltopdf官网地址

    wkhtmltopdf

    下载

    下载地址:https://wkhtmltopdf.org/downloads.html根据系统选择相应的版本
    这里以Linux为例:
    版本:wkhtmltox-0.12.6-1.centos7.x86_64.rpm

    安装

    1. 上传rpm文件到安装目录 /usr/local
    cd /usr/local
    
    1. 安装 rpm
    rpm -ivh wkhtmltox-0.12.6-1.centos7.x86_64.rpm
    
    1. 查看安装路径
    whereis wkhtmltopdf
    
    1. 字体安装(Linux)
      将 simsum.ttc 字体上传至 /usr/share/fonts/chinese/TrueType
      注:没有该路径就 mkdir 创建,字体也可以去windows系统 C:\Windows\Fonts 目录下找

    卸载

    rpm -qa |grep wkhtmlto
    rpm -e wkhtmltox-0.12.6-1.centos7.x86_64
    

    wkhtmltopdf自动生成文档

    方式一:通过wkhtmltopdf -H查看自动生成文档

    wkhtmltopdf -H
    

    方式二:访问官方查看自动生成文档
    https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

    JAVA集成wkhtmltopdf

    HtmlToPdf拦截器

    /**
     * HtmlToPdf拦截器
     */
    public class HtmlToPdfInterceptor extends Thread {
    
        private InputStream inputStream;
    
        public HtmlToPdfInterceptor(InputStream is){
            this.inputStream = inputStream;
        }
    
        public void run(){
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            try{
                inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    //打印内容
                    System.out.println(line.toString());
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try{
                    if(null != inputStreamReader){
                        inputStreamReader.close();
                    }
                    if(null != bufferedReader){
                        bufferedReader.close();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    
    }
    

    wkhtmlltopdf操作类

    public class HtmlToPdfOperator {
    
        /**
         * html转pdf
         * @param fromPath html路径,可以是磁盘路径,也可以是网络路径
         * @param toPath pdf保存路径
         * @return 转换成功返回true
         */
        public void convert(String fromPath, String toPath){
            File file = new File(toPath);
            File parent = file.getParentFile();
            //如果pdf保存路径不存在,则创建路径
            if(!parent.exists()){
                parent.mkdirs();
            }
            StringBuilder cmd = new StringBuilder();
            //加载wkhtmltopdf
            cmd.append(getWkhtmltopdfPath());
            //将纸张大小设置为自定义宽高的A4
            cmd.append(" --print-media-type");
            cmd.append(" --page-size A4");
            cmd.append(" --page-width 270mm");
            cmd.append(" --page-height 382mm");
    
            cmd.append(" ");
            cmd.append(fromPath);
            cmd.append(" ");
            cmd.append(toPath);
    
            try{
                Process proc = Runtime.getRuntime().exec(cmd.toString());
                HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
                HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
                error.start();
                output.start();
                proc.waitFor();
            }catch(Exception e){
                e.printStackTrace();
            }
    
        }
    
        /**
         * 获取wkhtmltopdf路径
         * @return
         */
        private String getWkhtmltopdfPath() {
            String wkhtmltopdfPath = "D:\\applocation\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
            return wkhtmltopdfPath;
        }
    
    }
    
    展开全文
  • JAVA HTML转pdf

    2016-07-11 17:43:33
    JAVA HTML转pdf,itext转换,已测试成功。所有需要jar已包括
  • java html转pdf工具类

    2016-12-15 10:43:55
    html转pdf工具类,可以直接将html转换成pdf
  • 主要介绍了Java实现Html转Pdf的方法,实例分析了java基于ITextRenderer类操作页面及系统自带字体生成pdf文件的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
  • java实现html转pdf,包含后端代码,html测试页面,pom依赖,jar包,如页面过于复杂需调整页面,有些样式itextpdf不支持,请寻找其它样式替换。
  • java HTML转PDF实现

    千次阅读 2022-03-15 22:31:04
    本文主要利用java itext解析HTML语句,输出为PDF文件。

    前言

    本文主要利用java itext解析HTML语句,输出为PDF文件。

    1.POM依赖

    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.5.1</version>
    </dependency>
    
    <!-- 支持中文 -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>
    <!-- 支持css样式渲染 -->
    <dependency>
        <groupId>org.xhtmlrenderer</groupId>
        <artifactId>flying-saucer-pdf-itext5</artifactId>
        <version>9.0.3</version>
    </dependency>
    

    2 html转pdf

    字体样式类

    import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.FontProvider;
    import com.itextpdf.text.pdf.BaseFont;
    
    public class MyFontProvider implements FontProvider {
    	private BaseColor bc;
    	private String fontname;
    	private String encoding;
    	private boolean embedded;
    	private boolean cached;
    	private float size;
    	private int style;
    	private BaseFont baseFont;
    
    	public MyFontProvider() {
    	}
    
    	public BaseColor getBc() {
    		return bc;
    	}
    
    	public void setBc(BaseColor bc) {
    		this.bc = bc;
    	}
    
    	public String getFontname() {
    		return fontname;
    	}
    
    	public void setFontname(String fontname) {
    		this.fontname = fontname;
    	}
    
    	public String getEncoding() {
    		return encoding;
    	}
    
    	public void setEncoding(String encoding) {
    		this.encoding = encoding;
    	}
    
    	public boolean isEmbedded() {
    		return embedded;
    	}
    
    	public void setEmbedded(boolean embedded) {
    		this.embedded = embedded;
    	}
    
    	public boolean isCached() {
    		return cached;
    	}
    
    	public void setCached(boolean cached) {
    		this.cached = cached;
    	}
    
    	public float getSize() {
    		return size;
    	}
    
    	public void setSize(float size) {
    		this.size = size;
    	}
    
    	public int getStyle() {
    		return style;
    	}
    
    	public void setStyle(int style) {
    		this.style = style;
    	}
    
    	public BaseFont getBaseFont() {
    		return baseFont;
    	}
    
    	public void setBaseFont(BaseFont baseFont) {
    		this.baseFont = baseFont;
    	}
    
    	public MyFontProvider(BaseColor bc, String fontname, String encoding, boolean embedded, boolean cached, float size,
    			int style, BaseFont baseFont) {
    		super();
    		this.bc = bc;
    		this.fontname = fontname;
    		this.encoding = encoding;
    		this.embedded = embedded;
    		this.cached = cached;
    		this.size = size;
    		this.style = style;
    		this.baseFont = baseFont;
    	}
    
    	public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) {
    		Font font = null;
    		if (baseFont == null) {
    			font = new Font();
    		} else {
    			font = new Font(baseFont);
    		}
    		font.setColor(arg5);
    		font.setFamily(fontname);
    		font.setSize(size);
    		font.setStyle(arg4);
    		return font;
    	}
    
    	public boolean isRegistered(String arg0) {
    		// TODO Auto-generated method stub
    		return true;
    	}
    
    }
    
    

    主方法类

    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.nio.charset.Charset;
    
    import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.pdf.BaseFont;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.tool.xml.Pipeline;
    import com.itextpdf.tool.xml.XMLWorker;
    import com.itextpdf.tool.xml.XMLWorkerHelper;
    import com.itextpdf.tool.xml.css.CssFilesImpl;
    import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
    import com.itextpdf.tool.xml.html.CssAppliersImpl;
    import com.itextpdf.tool.xml.html.HTML;
    import com.itextpdf.tool.xml.html.TagProcessorFactory;
    import com.itextpdf.tool.xml.html.Tags;
    import com.itextpdf.tool.xml.parser.XMLParser;
    import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
    import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
    import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
    import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
    
    public class Html2pdf {
    
    	public static void htmlTopdf(String html, File file) throws Exception {
    		try {
    			// step 1
    			Document document = new Document();
    			BaseFont bfChinese;
    			bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
    			MyFontProvider myFontProvider = new MyFontProvider(BaseColor.BLACK, "", "", false, false, 16, 1, bfChinese);
    			// step 2
    			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    			// step 3
    			document.open();
    
    			final TagProcessorFactory tagProcessorFactory = Tags.getHtmlTagProcessorFactory();
    			tagProcessorFactory.removeProcessor(HTML.Tag.IMG);
    
    			final CssFilesImpl cssFiles = new CssFilesImpl();
    			cssFiles.add(XMLWorkerHelper.getInstance().getDefaultCSS());
    			final StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
    			final HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(myFontProvider));
    			hpc.setAcceptUnknown(true).autoBookmark(true).setTagFactory(tagProcessorFactory);
    			final HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, writer));
    			final Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
    
    			final XMLWorker worker = new XMLWorker(pipeline, true);
    
    			final Charset charset = Charset.forName("UTF-8");
    			final XMLParser xmlParser = new XMLParser(true, worker, charset);
    
    			ByteArrayInputStream bais = new ByteArrayInputStream(html.getBytes("UTF-8"));
    			xmlParser.parse(bais, charset);
    
    			// step 5
    			document.close();
    			bais.close();
    		} catch (Exception e) {
    			throw new Exception(e);
    		}
    	}
    
    	public static void main(String[] args) {
    		String content = "<html><head><meta content=\"text/html;charset=UTF-8\"></meta></head><body><p>哈哈</p></body></html>";
    		File file = new File("d:/pdf2.pdf");
    		try {
    			htmlTopdf(content, file);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    
    	}
    
    }
    
    
    
    展开全文
  • javahtml转pdf

    2018-07-05 15:26:31
    java实现html转pdf,包括解决base64图片以及中文不显示问题
  • java后端将html转换pdf.zip
  • Java实现HTML转PDF的解决方案.docx
  • 记录一下利用freemarker 将html转换pdf的教程 pom.xml引入包 <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --> <dependency> <groupId>com.itextpdf</groupId> &...

    记录一下利用freemarker 将html转换pdf的教程

    pom.xml引入包

    <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.11</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
            <dependency>
                <groupId>com.itextpdf.tool</groupId>
                <artifactId>xmlworker</artifactId>
                <version>5.5.11</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-pdf -->
            <dependency>
                <groupId>org.xhtmlrenderer</groupId>
                <artifactId>flying-saucer-pdf</artifactId>
                <version>9.1.5</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-pdf-itext5 -->
            <dependency>
                <groupId>org.xhtmlrenderer</groupId>
                <artifactId>flying-saucer-pdf-itext5</artifactId>
                <version>9.1.5</version>
            </dependency>
    
    
            <!-- 解决中文字体问题 -->
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itext-asian</artifactId>
                <version>5.2.0</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>2.3.19</version>
            </dependency>

    解决中文不显示问题

    package com.express.excms.enroll.config;
    
    import com.itextpdf.text.Font;
    import com.itextpdf.text.pdf.BaseFont;
    import com.itextpdf.tool.xml.XMLWorkerFontProvider;
    
    /**
     * Created by IntelliJ IDEA.
     * User: 贝先 [ Cason mo ]
     * Date: 2021/11/12
     * Time: 14:46
     */
    public class AsianFontProvider extends XMLWorkerFontProvider {
        @Override
        public Font getFont(String fontname, String encoding, float size, final int style) {
            try {
                BaseFont bfChinese =BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
                return new Font(bfChinese, size, style);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.getFont(fontname, encoding, size, style);
        }
    }

    html转pdf

    package com.express.excms.enroll.utils;
    
    import com.express.excms.enroll.config.AsianFontProvider;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.tool.xml.XMLWorkerHelper;
    import lombok.extern.slf4j.Slf4j;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileOutputStream;
    import java.nio.charset.StandardCharsets;
    
    /**
     * Created by IntelliJ IDEA.
     * User: 贝先 [ Cason mo ]
     * Date: 2021/10/18
     * Time: 10:54
     */
    @Slf4j
    public class PDFUtils {
        /**
         * ByteArrayOutputStream pdf文件流
         * @param htmlContent 通过freemarker生成的html
         * @return
         * @throws Exception
         */
        public static ByteArrayOutputStream htmlToPdf(String htmlContent) throws Exception {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            Document document = new Document();
            PdfWriter pdfWriter = PdfWriter.getInstance(document, output);
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(pdfWriter,document,new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8)),null, StandardCharsets.UTF_8,new AsianFontProvider());
            document.close();
            return output;
        }
    
        /**
         * 写入到文件
         * @param htmlContent 通过freemarker生成的html
         * @param filePath 要写入的pdf文件地址
         * @throws Exception
         */
        public static void htmlToPdf(String htmlContent,String filePath) throws Exception {
            Document document = new Document();
            PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(filePath));
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(pdfWriter,document,new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8)),null, StandardCharsets.UTF_8,new AsianFontProvider());
            document.close();
        }
    }
    

    freemarker 解析并获取生成的html

            @Autowired
            private Configuration configuration;
    
    
    ......省略
    
    
    
            Configuration cfg = (Configuration) configuration.clone();
            cfg.clearTemplateCache();
            Template t = new Template(templateInDB.getName(), new StringReader(未渲染的html), configuration);
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, 要渲染的数据);
            try {
                ByteArrayOutputStream byteArrayOutputStream = PDFUtils.htmlToPdf(html);
                //获取pdf的base64
                byte[] bytes = byteArrayOutputStream.toByteArray();
           
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseResult.defaultFailed(e.getMessage());
            }
        

    效果图

     

    展开全文
  • itextpdf 使用之 html pdf 页眉页脚带图片,详见:https://blog.csdn.net/z1353095373/article/details/124762949
  • java 实现 html pdf(含图片)-附件资源
  • core-renderer-9176297.jar core-renderer-R8 (1).jar itext-asian-5.2.0.jar itextpdf-5.5.9.jar itext-pdfa-5.5.9.jar itext-xtra-5.5.9.jar xmlworker-5.5.9.jar 你要的jar 这里都有
  • 1.使用java代码调用压缩包内wkhtmltopdf.exe。 2.写入对应url及其其他参数 3.调用代码即可生成,亲测有效好用 4.内附示例代码
  • xhtmlrenderer 进行HTML转PDF,修改了core-renderer-R8的源码,兼容中英文换行,且保持对英文单词完整性,亲测可用。
  • JAVA实现PDF转HTML

    2020-10-29 16:53:08
    该包包含后端代码,转换控件,测试文件,正式项目应用表现正常,注意不能转换水印、印章这类特殊类型,且行且珍惜。
  • 其中包含了:iText-2.0.8.jar和core-render.jar这两个jar包。 ITextRenderer cannot be resolved to a type 错误就是因为缺少core-render.jar这个jar包
  • Java实现HTML文件转PDF文件

    热门讨论 2013-11-22 08:45:16
    实现思路: 1、通过URL获取当前HMTL页面的内容: URL urls = new URL(url);...4、把设置发了的HTML文件转化成PDF文件 //把HTML文件转化成PDF文件 htmlToPdf2(urlsource, fileName); 下载下来可以直接使用
  • java html转pdf手动分页

    千次阅读 2018-02-02 15:40:43
    com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream...
  • 搜索了好多篇例子,算是强拼硬凑成现在的样子,还算比较满意吧。 此包中包含可测试成功代码,关联模板、字体文件、jar等 希望能帮助到大家。 这篇文章的作者蛮厉害,有不少借鉴。 ...
  • 最近项目要改做一个需求,需求内容就是做一个批量导出的pdf功能,没接触过,所以在网上搜了很多内容,也碰到很多坑,现在自己总结一下,方便以后项目碰到。 1、首先maven依赖选择 刚开是用的是flying-saucer-pdf,...
  • java word转pdfhtml

    2018-11-16 11:48:48
    利用poi 把office转化为html,利用jacob把office转化为pdfhtml
  • java实现html转换pdf
  • html转pdf css控制

    2018-03-09 21:01:30
    html转pdf中css样式解析,解决解析样式出现异常问题,便于html转换为pdf
  • Java-html转pdf文件

    2017-12-07 16:32:30
    Java-html转pdf文件,支持中文,支持换行,-----------------

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 115,523
精华内容 46,209
关键字:

javahtml转pdf