iTextsharp PDF文字竖排

那位知道PDF文字竖排









像以上这样排

BaseFont bf0 = BaseFont.CreateFont("C:/WINDOWS/Fonts/STXINGKA.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            //创建PDF文档
                iTextSharp.text.Document document = new iTextSharp.text.Document();
            //创建写入器实例,PDF文件将会保存到这里
                iTextSharp.text.pdf.PdfWriter.GetInstance(document,new FileStream(Server.MapPath("demo.pdf"), FileMode.Create));
            //打开文档
                document.Open();
                iTextSharp.text.Font font = new iTextSharp.text.Font(bf0);
            //写入一个段落
                document.Add(new Paragraph("你好,这是第一页的PDF", font));
                document.Close();

  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/7613721
  • 这篇博客也不错, 你可以看下C#使用iTextSharp给PDF文件添加水印,PDF文件加密,PDF文件旋转
  • 除此之外, 这篇博客: IText生成PDF中的 2、PDF模板 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 应用场景:适合模板文本较多,动态内容较少的,只需要填写个别的空,空的内容较少
    优点:样子美观,开发容易便捷
    缺点:针对于循环,或者大文本上不适合,不易于扩展
    实现:
    需要准备用于创建PDF模板下载地址:链接:http://pan.baidu.com/s/1kVbRyPD 密码:k8ky
    首先用word编辑好需要的样式
    然后转成PDF再用这个软件打开
    点击编辑表单这里写图片描述
    这里就会留出一个个坑,然后我们将这里的坑编好编号

    //将需要填入模板的字段扔到Map(dataMap)里,distDir:生成的位置
    ITextUtil.genPdfByTemplate("pdftemp/CLFBX_TEMPLETE_10.pdf", distDir,dataMap);

    ITextUtil.java

    package com.yinker.oa.sys.util;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Element;
    import com.lowagie.text.Rectangle;
    import com.lowagie.text.pdf.AcroFields;
    import com.lowagie.text.pdf.BaseFont;
    import com.lowagie.text.pdf.PdfContentByte;
    import com.lowagie.text.pdf.PdfCopy;
    import com.lowagie.text.pdf.PdfGState;
    import com.lowagie.text.pdf.PdfImportedPage;
    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfStamper;
    import com.lowagie.text.pdf.PdfWriter;
    
    public class ITextUtil {
        // 所有者密码
        private static final String OWNERPASSWORD = "123123";
        private static final Logger logger = LoggerFactory.getLogger(ITextUtil.class);
    
        /**
         * 使用场景:同一个模板,打印多份,每份填充不同的内容
         * 
         * @例如:《共有人声明》,有几个共有人则打几份,虽然使用同一个模板,但是每一份都填充不同的信息。
         * @实现方式:先生成多个临时文件,然后复制过去
         * @param srcFile
         * @param distFile
         * @param dataList
         */
        public static void genPdfByTemplate(String srcFile, String distFile, List<Map<String, Object>> dataList) throws Exception {
            List<String> pdfList = new ArrayList<String>();
            if (null == dataList) {
                return;
            }
            if (dataList.size() <= 1) { // 只需要打印一次时没必要循环,因为循环的话会产生多余文件
                if (dataList.size() == 0) { // 为
                    dataList.add(new HashMap<String, Object>());
                }
                genPdfByTemplate(srcFile, distFile, dataList.get(0), false, "", false, "");
                return;
            }
    
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> dataMap = dataList.get(i);
                String tempDistFile = distFile + i;
                genPdfByTemplate(srcFile, tempDistFile, dataMap, false, "", false, "");
                pdfList.add(tempDistFile);
            }
            OutputStream out = new FileOutputStream(distFile);
            mergePdfFiles(pdfList, out);
        }
    
        public static void genPdfByTemplate(String srcFile, String distFile, Map<String, Object> dataMap) {
            genPdfByTemplate(srcFile, distFile, dataMap, false, "", false, "");
        }
    
        public static void genPdfByTemplate(String srcFile, String distFile, Map<String, Object> dataMap, boolean isWatermark, String wartermarkName) {
            genPdfByTemplate(srcFile, distFile, dataMap, isWatermark, wartermarkName, false, "");
        }
    
        public static void genPdfByTemplate(String srcFile, String distFile, Map<String, Object> dataMap, boolean isWatermark, String wartermarkName,
                        boolean isPwd, String pwd) {
            PdfReader reader = null;
            PdfStamper stamp = null;
            try {
                reader = new PdfReader(srcFile);
                // 模版文件目录
                stamp = new PdfStamper(reader, new FileOutputStream(distFile)); // 生成的输出流
                // 文字水印
                if (isWatermark) {
                    addWatermark(stamp, wartermarkName);
                }
                // 设置密码
                if (isPwd) {
                    stamp.setEncryption(pwd.getBytes(), OWNERPASSWORD.getBytes(), PdfWriter.ALLOW_SCREENREADERS, false);
                }
    
                AcroFields s = stamp.getAcroFields();
                for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (null != value) {
                        s.setField(key, value.toString());
                    }
                }
    
                stamp.setFormFlattening(true); // 这句不能少
            } catch (IOException e) {
                logger.error("生成pdf文件失败:srcFile:" + srcFile + ";desFile:" + distFile, e);
            } catch (DocumentException e) {
                logger.error("生成pdf文件失败:srcFile:" + srcFile + ";desFile:" + distFile, e);
            } finally {
                try {
                    stamp.close();
                    reader.close();
                } catch (DocumentException e) {
                    logger.error("生成pdf文件失败:srcFile:" + srcFile + ";desFile:" + distFile, e);
                } catch (IOException e) {
                    logger.error("生成pdf文件失败:srcFile:" + srcFile + ";desFile:" + distFile, e);
                }
            }
        }
    
        /**
         * 复制pdf文档(根据多个文件流直接生成PDF文件)
         * 
         * @param sourceFileList
         *            源文件列表
         * @param targetFile
         *            目标文件
         */
        public static void copyPdf(List<byte[]> sourceFileList, String targetFile) throws Exception {
            try {
                Document document = new Document();
                PdfCopy copy = new PdfCopy(document, new FileOutputStream(targetFile));
                document.open();
                for (byte[] sourceFile : sourceFileList) {
                    PdfReader pdfReader = new PdfReader(sourceFile);
                    int n = pdfReader.getNumberOfPages();
                    for (int i = 1; i <= n; i++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(pdfReader, i);
                        copy.addPage(page);
                    }
                }
                document.close();
            } catch (IOException e) {
                logger.error("根据多个文件流直接生成pdf文件失败:targetFile:" + targetFile, e);
                throw new Exception("根据多个文件流直接生成pdf文件失败:targetFile:" + targetFile);
            } catch (DocumentException e) {
                logger.error("根据多个文件流直接生成pdf文件失败:targetFile:" + targetFile, e);
                throw new Exception("根据多个文件流直接生成pdf文件失败:targetFile:" + targetFile);
            }
        }
    
        /**
         * 复制pdf文档
         * 
         * @param sourceFile
         *            源文件
         * @param targetFile
         *            目标文件
         */
        public static void copyPdf(byte[] sourceFile, String targetFile) throws Exception{
            PdfReader pdfReader;
            try {
                pdfReader = new PdfReader(sourceFile);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(targetFile));
                pdfStamper.close();
            } catch (IOException e) {
                logger.error("复制pdf文件失败:targetFile:" + targetFile, e);
                throw new Exception("复制pdf文件失败:targetFile:" + targetFile);
            } catch (DocumentException e) {
                logger.error("复制pdf文件失败:targetFile:" + targetFile, e);
                throw new Exception("复制pdf文件失败:targetFile:" + targetFile);
            }
        }
    
        /**
         * 创建pdf文件
         * 
         * @param writer
         * @param document
         * @param headerStr
         * @param footerStr
         */
        public static PdfWriter createPdf(String tempFile, Document document, String headerLeft, String headerRight) {
            // 横线
            PdfWriter writer = null;
            try {
                writer = PdfWriter.getInstance(document, new FileOutputStream(tempFile));
            } catch (DocumentException e) {
                logger.error("创建pdf文件失败:tempFile:" + tempFile, e);
            } catch (FileNotFoundException e) {
                logger.error("创建pdf文件失败:tempFile:" + tempFile, e);
            }
    
            return writer;
        }
    
        /**
         * 多个PDF合并功能
         * 
         * @param files多个PDF的文件路径
         * @param os生成的输出流
         */
        public static void mergePdfFiles(List<String> pdfList, OutputStream os) {
            try {
                Document document = new Document(new PdfReader(pdfList.get(0)).getPageSize(1));
                PdfCopy copy = new PdfCopy(document, os);
                document.open();
                for (int i = 0; i < pdfList.size(); i++) {
                    PdfReader reader = new PdfReader(pdfList.get(i));
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                }
                document.close();
            } catch (IOException e) {
                logger.error("多个PDF合并失败:", e);
            } catch (DocumentException e) {
                logger.error("多个PDF合并失败:", e);
            } finally {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error("多个PDF合并失败:", e);
                }
            }
        }
    
        /**
         * 添加水印
         * 
         * @param pdfStamper
         * @param waterMarkName
         */
        public static void addWatermark(PdfStamper pdfStamper, String waterMarkName) {
            PdfContentByte content = null;
            BaseFont base = null;
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            try {
                // 设置字体
                base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (base == null || pdfStamper == null) {
                    return;
                }
                // 设置透明度为0.4
                gs.setFillOpacity(0.1f);
                gs.setStrokeOpacity(0.1f);
                int toPage = pdfStamper.getReader().getNumberOfPages();
                for (int i = 1; i <= toPage; i++) {
                    pageRect = pdfStamper.getReader().getPageSizeWithRotation(i);
                    // 计算水印X,Y坐标
                    float x = pageRect.getWidth() / 2;
                    float y = pageRect.getHeight() / 2;
                    // 获得PDF最顶层
                    content = pdfStamper.getOverContent(i);
                    content.saveState();
                    // set Transparency
                    content.setGState(gs);
                    content.beginText();
                    content.setFontAndSize(base, 60);
                    // 水印文字成45度角倾斜
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, 45);
                    content.endText();
                }
            } catch (Exception ex) {
                logger.error("添加水印失败:", ex);
            } finally {
                content = null;
                base = null;
                pageRect = null;
            }
        }
    }