c# 生成pdf文件,经测试,生成的pdf很完美,无损失,比起itext等网上流行的那些生成pdf的更完美。

预准备:

1.安装microsoft office

2. 安装microsoft office生成pdf插件SaveAsPDFandXPS.exe,可以在msdn上免费得到。

3.在您的工程项目里添加引用:

COM : Microsoft Office 12.0 Object Library   ; 

.NET : Microsoft.Office.Interop.Excel  、Microsoft.Office.Interop.Word、Microsoft.Office.Interop.PowerPoint  

开始编程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.IO;

public class ExportFormatPdf
    {
        /// <summary>
        /// 转换生成pdf格式的文件
        /// 支持的文件类型(.doc、.docx、.mht、.htm、.xls、.xlsx、.ppt、pptx)
        /// </summary>
        /// <param name="fileName">源文件</param>
        /// <param name="outputFileName">目标文件</param>
        /// <returns></returns>
        public static bool ExportPdf(string fileName, string outputFileName)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(outputFileName))
                return false;


            if (!File.Exists(fileName))
                return false;
            string extension = Path.GetExtension(fileName);
            string formatExtension = Path.GetExtension(outputFileName);
            if (string.IsNullOrEmpty(extension) || string.IsNullOrEmpty(formatExtension))
                return false;
            if (formatExtension != ".pdf")
                return false;
            switch (extension)
            {
                case ".doc":
                    return WordExportAsPdf(fileName, outputFileName);
                case ".docx":
                    return WordExportAsPdf(fileName, outputFileName);
                case ".mht":
                    return WordExportAsPdf(fileName, outputFileName);
                case ".htm":
                    return WordExportAsPdf(fileName, outputFileName);
                case ".html":
                    return WordExportAsPdf(fileName, outputFileName);
                case ".xls":
                    return ExcelExportAsPdf(fileName, outputFileName);
                case ".xlsx":
                    return ExcelExportAsPdf(fileName, outputFileName);
                case ".ppt":
                    return PowerPointExportAsPdf(fileName, outputFileName);
                case ".pptx":
                    return PowerPointExportAsPdf(fileName, outputFileName);
                default:
                    return false;
            }
        }


        /// <summary>
        /// 转换为pdf文件,适合(.doc、.docx、.mht、.htm文件类型)
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="outputFileName"></param>
        /// <returns></returns>
        private static bool WordExportAsPdf(string fileName, string outputFileName)
        {
            bool isSucceed = false;
            Word.WdExportFormat fileFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            Word._Application wordApp = null;
            if (wordApp == null) wordApp = new Word.Application();
            Word._Document wordDoc = null;


            try
            {
                wordDoc = wordApp.Documents.Open(fileName);
                wordDoc.ExportAsFixedFormat(outputFileName, fileFormat);
                isSucceed = true;
            }
        
            finally
            {
                if (wordDoc != null)
                {
                    wordDoc.Close();
                    wordDoc = null;
                }
                if (wordApp != null)
                {
                    wordApp.Quit();
                    wordApp = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }


            return isSucceed;
        }


        /// <summary>
        /// 转换为pdf文件,适合(.xls、.xlsx文件类型)
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="outputFileName"></param>
        /// <returns></returns>
        private static bool ExcelExportAsPdf(string fileName, string outputFileName)
        {
            bool isSucceed = false;
            Excel.XlFixedFormatType fileFormat = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
            Excel.Application excelApp = null;
            if (excelApp == null) excelApp = new Excel.Application();
            Excel.Workbook workBook = null;


            try
            {
                workBook = excelApp.Workbooks.Open(fileName);
                workBook.ExportAsFixedFormat(fileFormat, outputFileName);
                isSucceed = true;
            }
         
            finally
            {
                if (workBook != null)
                {
                    workBook.Close();
                    workBook = null;
                }
                if (excelApp != null)
                {
                    excelApp.Quit();
                    excelApp = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }


            return isSucceed;
        }


        /// <summary>
        /// 转换为pdf文件,适合(.ppt、pptx文件类型)
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="outputFileName"></param>
        /// <returns></returns>
        private static bool PowerPointExportAsPdf(string fileName, string outputFileName)
        {
            bool isSucceed = false;
            PowerPoint.PpFixedFormatType fileFormat = PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF;


            PowerPoint.Application pptxApp = null;
            if (pptxApp == null) pptxApp = new PowerPoint.Application();
            PowerPoint.Presentation presentation = null;


            try
            {
                presentation = pptxApp.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                presentation.ExportAsFixedFormat(outputFileName, fileFormat);
                isSucceed = true;
            }
          
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    presentation = null;
                }
                if (pptxApp != null)
                {
                    pptxApp.Quit();
                    pptxApp = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }


            return isSucceed;
        }
    }


完毕 ,拿来一个上述支持的格式的文件来做试试,您将看到生成完美的pdf文件了。自从有了它,本人终于放松神经了,相信很多需要生成pdf的同仁们看完这篇文章后也该放松神经了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我会为你提供一个使用 pdfbox 和 iText 生成 PDF 文件以及读取 PDF 文件内容的示例代码,同时支持中文。 生成 PDF 文件代码示例: ``` import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter; public class PDFGenerator { public static void main(String[] args) throws Exception { // 生成 pdfbox 生成PDF 文件 generatePdfByPdfbox(); // 生成 iText 生成PDF 文件 generatePdfByItext(); } private static void generatePdfByPdfbox() throws Exception { // 创建一个 PDF 文档 PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page); // 创建一个字体对象 PDType0Font font = PDType0Font.load(document, PDFGenerator.class.getClassLoader().getResourceAsStream("FZXBSJW.TTF")); // 创建一个 ContentStream 对象 PDPageContentStream contentStream = new PDPageContentStream(document, page); // 添加文字 contentStream.setFont(font, 12); contentStream.beginText(); contentStream.newLineAtOffset(100, 700); contentStream.showText("Hello, PDFBox!"); contentStream.endText(); // 添加图片 PDImageXObject image = JPEGFactory.createFromStream(document, PDFGenerator.class.getClassLoader().getResourceAsStream("example.jpg")); contentStream.drawImage(image, 100, 500, 300, 200); // 关闭 ContentStream 对象 contentStream.close(); // 保存 PDF 文件 File file = new File("pdfbox.pdf"); document.save(file); document.close(); } private static void generatePdfByItext() throws Exception { // 创建一个 iText 文档 Document document = new Document(PageSize.A4, 50, 50, 50, 50); // 创建一个字体对象 BaseFont font = BaseFont.createFont(PDFGenerator.class.getClassLoader().getResource("FZXBSJW.TTF").getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); // 创建一个 Writer 对象 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("itext.pdf")); // 打开文档 document.open(); // 添加文字 Paragraph paragraph = new Paragraph("Hello, iText!", new com.itextpdf.text.Font(font, 12)); document.add(paragraph); // 添加图片 PdfContentByte cb = writer.getDirectContent(); com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(PDFGenerator.class.getClassLoader().getResource("example.jpg")); image.scaleToFit(300, 200); image.setAbsolutePosition(100, 500); cb.addImage(image); // 关闭文档 document.close(); } } ``` 读取 PDF 文件内容代码示例: ``` import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.PdfTextExtractor; public class PDFReader { public static void main(String[] args) throws Exception { // 读取 pdfbox 生成PDF 文件 readPdfByPdfbox(); // 读取 iText 生成PDF 文件 readPdfByItext(); } private static void readPdfByPdfbox() throws Exception { File file = new File("pdfbox.pdf"); PDDocument document = PDDocument.load(file); PDFTextStripper stripper = new PDFTextStripper(); String content = stripper.getText(document); System.out.println(content); document.close(); } private static void readPdfByItext() throws Exception { File file = new File("itext.pdf"); PdfReader reader = new PdfReader(file.getPath()); String content = PdfTextExtractor.getTextFromPage(reader, 1); System.out.println(content); reader.close(); } } ``` 这样,你就可以使用 pdfbox 和 iText 生成和读取 PDF 文件了。注意:在生成 PDF 文件时,需要引入相应的字体文件,否则中文可能无法正确显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值