zoukankan      html  css  js  c++  java
  • 滴水穿石Java 生成PDF文件iText使用之插入图片和中文乱码

    iText默认是不支持中文的,处理中文需要用到itext-asian.jar包,关键代码:

    处理中文:

    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);    
    Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
    添加图片:
    Image image = Image.getInstance("http://a.fsdn.com/con/icons/it/itext@sf.net/logo_itext.gif"); 
    完成实例代码:
    import java.io.FileOutputStream;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.Image;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.BaseFont;
    import com.itextpdf.text.pdf.PdfWriter;
    public class TestPdf { 
        public static void main(String[] args) throws Exception{
            //step1  
            Document document = new Document();  
            //step2  
            PdfWriter.getInstance(document, new FileOutputStream("first.pdf"));  
            //step3  
            document.open();  
            //step4  
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);      
            Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);  
            Paragraph p = new Paragraph("Hello World,this is my first pdf!这是我的第一个pdf实例",fontChinese);
            document.add(p);  
            //添加一个图片  
            Image image = Image.getInstance("http://a.fsdn.com/con/icons/it/itext@sf.net/logo_itext.gif");  
            document.add(image);  
            //step5 
            document.close();   
        }
    } 
    运行效果图:

  • 相关阅读:
    不容易发现的错误
    Element-UI 笔记
    工作中常用的操作/经验
    记录一些前端强大的插件
    HttpContext.Current.ApplicationInstance.Application vs HttpContext.Current.Application
    What Is a Replay Attack?
    ASP.NET's Data Storage Objects
    JSON Web Token (JWT) RFC7519
    Session-State Modes
    After change SessionID data in Session variables is lost
  • 原文地址:https://www.cnblogs.com/nexiyi/p/2820510.html
Copyright © 2011-2022 走看看