C# .net PDF文件预览

 

首先引用 O2S.Components.PDFRender4NET

( 云盘准备好了:链接:https://pan.baidu.com/s/16l5ktVGdJeqdW1_ceydm4g   提取码:xqmh)

然后在代码中引入

using O2S.Components.PDFRender4NET;

 

 

核心代码

//图片的清晰度,数字越大越清晰
public enum Definition
{
    One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10
}

//判断文件是否存在
private bool FileIsExists(string path)
{
    if (System.IO.File.Exists(path))
        return true;
    else
        return false;
}


/// <summary>
/// 将PDF文档转换为图片的方法
/// </summary>
/// <param name="pdfInputPath">PDF文件路径</param>
/// <param name="imageOutputPath">图片输出路径</param>
/// <param name="imageName">生成图片的名字</param>
///// <param name="startPageNum">从PDF文档的第几页开始转换</param>
///// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>       
///// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
///// <param name="imageFormat">设置所需图片格式</param>       
private  string  ConvertPDF2Image(string pdfInputPath, string imageOutputPath,string imageName)
{
   //为了测试方便,把几个参数固定住
    //格式 
    ImageFormat imageFormat = ImageFormat.Jpeg;
    //清晰度
    Definition definition = Definition.Ten;
    //起止页码
    int startPageNum= 1;
    int endPageNum = 1;
    //生成图片名称
    //string imageName = "test";

    PDFFile pdfFile = PDFFile.Open(pdfInputPath);
    if (!Directory.Exists(imageOutputPath))
    {
        Directory.CreateDirectory(imageOutputPath);
    }
    if (startPageNum <= 0)
    {
        startPageNum = 1;
    }
    if (endPageNum > pdfFile.PageCount)
    {
        endPageNum = pdfFile.PageCount;
    }
    if (startPageNum > endPageNum)
    {
        int tempPageNum = startPageNum;
        startPageNum = endPageNum;
        endPageNum = startPageNum;
    }
    // start to convert each page
  //多页循序产生图片
    string imageOutputRet = "";
    for (int i = startPageNum; i <= endPageNum; i++)
    {
        Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition);
        imageOutputRet = imageOutputPath + imageName  + i.ToString()+ "." + imageFormat.ToString();
        ////防止图片文件重复【暂不用】
        //int sign = 1;
        //while(this.FileIsExists(imageOutputRet))//存在
        //{
        //    imageOutputRet = imageOutputPath + imageName + i.ToString() +"_"+sign.ToString() + "." + imageFormat.ToString();
        //    sign++;
        //}               
        pageImage.Save(imageOutputRet, imageFormat);
        pageImage.Dispose();
    }
    pdfFile.Dispose();
    return imageOutputRet;
}

        

 

posted @ 2020-04-07 15:42  深海地平线  阅读(5479)  评论(0编辑  收藏  举报