.net 简单实现在H5中将word、jpg、png转成PDF给PDF添加水印并且控制样式和可视化编辑


在写完这三个需求之后 word转PDFPDF添加水印,并控制显示的页数JPG转PDF

新的需求接踵而来 将这三个功能合并 防灾H5页面上 边学习边记录,后面还会整理一些做微信深度开发时所用到的一些技术

下面看实际效果

 

针对目前的需求只实现了这些功能 如果运用到其他项目中扩展的话会继续更新

 

用到的引用

 

下面上代码

 

前端页面

@{
    ViewBag.Title = "Home Page";
}
<script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/important/jquery.scrollLoading.min.js"></script>
<script src="~/Scripts/important/fileUpload.min.js"></script>
<div style="display:flex;">
    <div id="pdfsrc" style="border:1px solid red;height:700px;width:1000px;margin-top:50px;">

        <embed src="http://localhost:44344/pdfjs/web/viewer.html?file=http://localhost:44344/aaa/aca.pdf" width="100%" height="100%"></embed>
    </div>


    <div style="border:1px solid red;height:700px;width:1000px;margin-top:50px;margin-left:20px;">
        <label>水印内容</label> <input type="text" id="mark" /><br />
        <label>开始页</label> <input type="number" id="pageindex" /><br />
        <label>可以看几页</label> <input type="number" id="pagesize" /><br />
        <label>角度</label> <input type="number" id="jd" /><br />
        <label>大小</label> <input type="number" id="dx" /><br />

        <label>颜色</label>
        <select id="color">
            <option value="Blue" selected="selected">蓝色</option>
            <option value="Orange">橙色</option>
            <option value="Olive">黄褐色</option>
            <option value="Navy">海军蓝</option>
            <option value="Moccasin">蛇皮色</option>
            <option value="MidnightBlue">深蓝</option>
            <option value="Lime">石灰色</option>
            <option value="Maroon">紫褐色</option>
            <option value="Magenta">桃红色</option>
            <option value="PapayaWhip">番木瓜色</option>
            <option value="SteelBlue">钢蓝色</option>
            <option value="White">白色</option>
            <option value="Yellow">黄色</option>
            <option value="Azure">蔚蓝色</option>
            <option value="Black">黑色</option>
            <option value="Gold">金色</option>
            <option value="Green">绿色</option>
            <option value="Gray">灰色</option>
            <option value="Ivory">象牙色</option>

        </select>
        <input type="button" value="添加水印" id="tjsy" class="search-btn ml5" style="width:65px">

        <br />
        <input type="text" />
        <input type="file" style="display:none;" name="fileToUpload" onchange="fileSelected();" value="" id="openw" class="none" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword" />
        <input type="button" value="Word转PDF" id="isoks-upload" class="search-btn ml5" style="width:105px">
        <input type="hidden" id="urls" />
        <input type="hidden" id="urlsT" /><br />

        <input type="text" />
        <input type="file" style="display:none;" name="fileToUpload" onchange="fileSelectedimage();" value="" id="openimage" class="none" accept="image/png,image/jpeg" />
        <input type="button" value="图片转PDF" id="isoks_images" class="search-btn ml5" style="width:105px" />

    </div>
</div>

<script>

    $(function () {
        isoks_upload();
        isoks_images();
        $("#tjsy").click(function () {
            var url = $("#urls").val();
            var mark = $("#mark").val();
            if (mark == "" || url == "") {
                alert("请上传文件或填写水印内容");
                return false;
            }
            var pageIndex = $("#pageindex").val();
            var pageSize = $("#pagesize").val();
            var color = $("#color").val();
            var jd = $("#jd").val();
            var dx = $("#dx").val();

            $.post("/Home/PDFAddMark", { url, mark, pageIndex, pageSize, color,jd,dx }, function (msg) {
                if (msg.State) {
                    $("#pdfsrc").html("");
                    $("#pdfsrc").html("  <embed src='http://localhost:44344/pdfjs/web/viewer.html?file=" + msg.Msg + "' width='100%' height='100%'></embed>");
                    $("#urlsT").val(msg.Msg);
                }
                else {
                    alert("失败");
                    return false;
                }
            });
        })
    });

    /**
 * 一键上传
 */

    function fileSelected() {

        var file = $this[0].files[0];
        if (file) {
            var fileSize = 0;
            if (file.size > 1024 * 1024)
                fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            else
                fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
        }
        uploadFile(file);
    }

    function uploadFile(file) {
        var pageindex = $("#pageindex").val();
        var pagesize = $("#pagesize").val();

        var fd = new FormData();
        fd.append($this.attr('name'), file);
        file_uploadFileParam(fd, $this.attr('name'), "/Home/fileToUpload?pageIndex=" + pageindex + "&pageSize=" + pagesize, null, uploadComplete, uploadFailed, uploadCanceled)
    }


    function uploadComplete(evt) {
        var msg = evt.target.responseText;
        console.log(msg);
        msg = $.parseJSON(msg);

        if (msg.State) {
            $this.prev().val(msg.Msg);
            console.log(msg.Msg);
            $("#pdfsrc").html("");
            $("#pdfsrc").html("  <embed src='http://localhost:44344/pdfjs/web/viewer.html?file=" + msg.Msg + "' width='100%' height='100%'></embed>");
            $("#urls").val(msg.Msg);
            alert("成功");
            //$this.prev().prev().attr("src", msg.Msg);
        } else {
            //$.alertboxsml(msg.Msg);
            //window.location.href = "/product/index";
            alert("失败");
        }
    }

    function uploadFailed(evt) {
        $.alertboxsml("上传失败!");
    }

    function uploadCanceled(evt) {
        $.alertboxsml("上传中断!");
    }
    //一键上传
    function isoks_upload() {

        $("#isoks-upload").click(function () {
            $this = $("#openw");
            $this.click();
        })
    }


    //一键上传
    function isoks_images() {
        $("#isoks_images").click(function () {
            $this = $("#openimage");
            $this.click();
        })
    }

    function fileSelectedimage() {

        var file = $this[0].files[0];
        if (file) {
            var fileSize = 0;
            if (file.size > 1024 * 1024)
                fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            else
                fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
        }
        uploadFileimage(file);
    }

    function uploadFileimage(file) {
        var pageindex = $("#pageindex").val();
        var pagesize = $("#pagesize").val();

        var fd = new FormData();
        fd.append($this.attr('name'), file);
        file_uploadFileParam(fd, $this.attr('name'), "/Home/ImageToPdf", null, uploadCompleteimg, uploadFailedimg, uploadCanceledimg)
    }

    function uploadCompleteimg(evt) {
        var msg = evt.target.responseText;
        console.log(msg);
        msg = $.parseJSON(msg);

        if (msg.State) {
            $this.prev().val(msg.Msg);
            console.log(msg.Msg);
            $("#pdfsrc").html("");
            $("#pdfsrc").html("  <embed src='http://localhost:44344/pdfjs/web/viewer.html?file=" + msg.Msg + "' width='100%' height='100%'></embed>");
            $("#urls").val(msg.Msg);
            alert("成功");
            //$this.prev().prev().attr("src", msg.Msg);
        } else {
            //$.alertboxsml(msg.Msg);
            //window.location.href = "/product/index";
            alert("失败");
        }
    }

    function uploadFailedimg(evt) {
        $.alertboxsml("上传失败!");
    }

    function uploadCanceledimg(evt) {
        $.alertboxsml("上传中断!");
    }

</script>

 

Controller里面的代码

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KSir;
namespace PDFTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 将word转为pdf
        /// </summary>
        /// <param name="pageIndex">开始页</param>
        /// <param name="pageSize">可以看几页</param>
        /// <param name="fileToUpload">word文件</param>
        /// <returns></returns>
        public ActionResult fileToUpload(string pageIndex, string pageSize, HttpPostedFileBase fileToUpload)
        {
            try
            {
                if (fileToUpload == null) return Json_IsoksError("系统错误!");
                var t = KsirUpload.Isoks_UploadFile(fileToUpload, "PDF");
                if (string.IsNullOrWhiteSpace(t))
                {
                    return Json_IsoksError("哎呀,出错了");
                }
                var suffix = Path.GetExtension(fileToUpload.FileName);
                var pd = PDFInfo.WordToPDFWithOffice(t, t.Replace(suffix, ".pdf"), pageIndex, pageSize);
                //var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString();
                var url = ConfigurationManager.AppSettings["ImgPath"];
                string path = url + "/UploadFiles/AnotherFile/PDF/" + Path.GetFileName(t).Replace(suffix, ".pdf");
                return Json_IsoksSuccess(path);
            }
            catch (Exception ex)
            {
                return Json_IsoksError("哎呀,出错了");
            }
        }

        /// <summary>
        /// 给PDF添加水印
        /// </summary>
        /// <param name="url">PDF本地地址</param>
        /// <param name="mark">水印内容</param>
        /// <param name="pageIndex">开始页</param>
        /// <param name="pageSize">可以看几页</param>
        /// <param name="color">水印颜色</param>
        /// <param name="jd">水印角度</param>
        /// <param name="dx">水印大小</param>
        /// <returns></returns>
        public ActionResult PDFAddMark(string url, string mark, string pageIndex, string pageSize, string color, float jd = -45, float dx = 24)
        {
            string str = System.AppDomain.CurrentDomain.BaseDirectory + url.Replace(ConfigurationManager.AppSettings["ImgPath"], "");
            //string strPhycicsPath = Server.MapPath(url);
            var suffix = Path.GetFileName(str).Replace(".pdf", "") + "1.pdf";

            var marks = KSir.PDFInfo.PDFAddMark(str, str.Replace(Path.GetFileName(str), suffix), mark, pageIndex, pageSize, color, jd,dx);
            if (marks)
            {
                return Json_IsoksSuccess(url.Replace(Path.GetFileName(str), suffix));
            }
            else
            {
                return Json_IsoksError("失败");
            }
        }

        /// <summary>
        /// 图片转PDF
        /// </summary>
        /// <param name="fileToUpload"></param>
        /// <returns></returns>
        public ActionResult ImageToPdf(HttpPostedFileBase fileToUpload)
        {
            try
            {
                if (fileToUpload == null) return Json_IsoksError("系统错误!");
                var t = KsirUpload.Isoks_UploadFile(fileToUpload, "PDF");
                if (string.IsNullOrWhiteSpace(t))
                {
                    return Json_IsoksError("哎呀,出错了");
                }
                var suffix = Path.GetExtension(fileToUpload.FileName);
                var pd = PDFInfo.ConvertJPG2PDF(t, t.Replace(suffix, ".pdf"));
                //var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString();
                var url = ConfigurationManager.AppSettings["ImgPath"];
                string path = url + "/UploadFiles/AnotherFile/PDF/" + Path.GetFileName(t).Replace(suffix, ".pdf");
                return Json_IsoksSuccess(path);
            }
            catch (Exception ex)
            {
                return Json_IsoksError("哎呀,出错了");
            }
        }


        public bool IsoksIsNullOrWhiteSpace(params string[] value)
        {
            for (int i = 0; i < value.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(value[i])) return false;
            }
            return true;
        }

        #region isoks-json

        /// <summary>
        /// Json-Success
        /// Author:
        /// Return:[{State:true,Msg=Msg}]
        /// </summary>
        /// <param name="c"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public ActionResult Json_IsoksSuccess(object Msg, JsonRequestBehavior GetOrPost = JsonRequestBehavior.DenyGet)
        {
            return Json(new { State = true, Msg = Msg }, GetOrPost);
        }

        /// <summary>
        /// Json-Error
        /// Author:
        /// Return:[{State:true,Msg=Msg}]
        /// </summary>
        /// <param name="c"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public ActionResult Json_IsoksError(object Msg, JsonRequestBehavior GetOrPost = JsonRequestBehavior.DenyGet)
        {
            return Json(new { State = false, Msg = Msg }, GetOrPost);
        }

        public static class Isok
        {
            /// <summary>
            /// json-get
            /// </summary>
            public const JsonRequestBehavior Get = JsonRequestBehavior.AllowGet;
        }
        #endregion

    }
}

 

KsirUpload.cs 代码

using System;
using System.Configuration;
using System.IO;
using System.Threading.Tasks;
using System.Web;

namespace KSir
{
    public static class KsirUpload
    {
        public static string Isoks_UploadImg(HttpPostedFileBase fileToUpload, string pathUri)
        {
            try
            {
                if (fileToUpload == null) return string.Empty;
                //获取文件后缀
                var suffix = Path.GetExtension(fileToUpload.FileName);
                if (string.IsNullOrWhiteSpace(suffix)) return string.Empty;
                if (suffix.ToLower() != ".jpg" && suffix.ToLower() != ".png" && suffix.ToLower() != ".gif" && suffix.ToLower() != ".bmp" && suffix.ToLower() != ".mp4" && suffix.ToLower() != ".avi") return string.Empty;
                var stream = fileToUpload.InputStream;
                Random r = new Random();
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + r.Next(9) + r.Next(9) + r.Next(9) + r.Next(9);
                string directory = HttpContext.Current.Server.MapPath("/UploadFiles/" + pathUri + "/");
                //判断目录是否存在  
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString();
                string path = url + "/UploadFiles/" + pathUri + "/" + fileName + suffix;
                var _path = directory + fileName + suffix;
                fileToUpload.SaveAs(_path);
                return path;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public static string Isoks_UploadFile(HttpPostedFileBase fileToUpload, string pathUri)
        {
            try
            {
                if (fileToUpload == null) return string.Empty;
                //获取文件后缀
                var suffix = Path.GetExtension(fileToUpload.FileName);
                if (string.IsNullOrWhiteSpace(suffix)) return string.Empty;
                var stream = fileToUpload.InputStream;
                Random r = new Random();
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + r.Next(9) + r.Next(9) + r.Next(9) + r.Next(9);
                string directory = HttpContext.Current.Server.MapPath("/UploadFiles/AnotherFile/" + pathUri + "/");
                //判断目录是否存在  
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string url = ConfigurationManager.AppSettings["ImgPath"];
                //var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString();
                string path = url + "/UploadFiles/AnotherFile/" + pathUri + "/" + fileName + suffix;
                var _path = directory + fileName + suffix;
                fileToUpload.SaveAs(_path);
                return _path;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public static string Isoks_UploadExcel(HttpPostedFileBase fileToUpload, string pathUri)
        {
            try
            {
                if (fileToUpload == null) return string.Empty;
                //获取文件后缀
                var suffix = Path.GetExtension(fileToUpload.FileName);
                if (string.IsNullOrWhiteSpace(suffix)) return string.Empty;
                var stream = fileToUpload.InputStream;
                Random r = new Random();
                var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + r.Next(9) + r.Next(9) + r.Next(9) + r.Next(9);
                string directory = HttpContext.Current.Server.MapPath("/UploadFiles/AnotherFile/" + pathUri + "/");

                //判断目录是否存在  
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string path = "/UploadFiles/AnotherFile/" + pathUri + "/" + fileName + suffix;
                var _path = directory + fileName + suffix;
                fileToUpload.SaveAs(_path);
                return _path;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public static byte[] StreamToBytes(Stream stream)
        {
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return buffer;
        }


    }
}

 

PDFInfo.cs 代码

using iTextSharp.text.pdf;
using Microsoft.Office.Interop.Word;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;

namespace KSir
{
    public static class PDFInfo
    {
        /// <summary>
        /// 将word转成PDF office
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static bool WordToPDFWithOffice(string sourcePath, string targetPath, string fromPage, string toPage)
        {
            bool result = false;
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Document document = null;
            try
            {
                application.Visible = false;
                document = application.Documents.Open(sourcePath);
                /*
                 参数参考 https://docs.microsoft.com/zh-cn/office/vba/api/visio.document.exportasfixedformat
                 */
                int pageindex = 1;
                object Nothing = Missing.Value;
                if (!string.IsNullOrEmpty(fromPage))
                {
                    pageindex = int.Parse(fromPage);
                }
                int pagesize = document.ComputeStatistics(WdStatistic.wdStatisticPages, ref Nothing);
                if (!string.IsNullOrEmpty(toPage))
                {
                    pagesize = int.Parse(toPage);
                }

                document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportFromTo, pageindex, pagesize);
                result = true;
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.Message);
                result = false;
            }
            finally
            {
                document.Close();
            }
            return result;
        }

        /// <summary>
        /// 给PDF文件添加水印
        /// </summary>
        /// <param name="pdfPath">需要添加水印的pdf文件路径</param>
        /// <param name="targetPath">添加成功之后的文件路径和文件名</param>
        /// <param name="marks">水印内容</param>
        /// <param name="fromPage">可以从第几页开始看</param>
        /// <param name="toPage">可以看多少页</param>
        /// <returns></returns>
        public static bool PDFAddMark(string pdfPath, string targetPath, string marks, string pageindex, string pagesize, string color, float jd = -45, float dx = 24)
        {
            bool result = false;
            try
            {




                //创建一个新的PDF实例。然后导入PDF文件。 
                Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
                pdf.LoadFromFile(pdfPath);

                //这里是因为Spire的版本问题 第一页会被添加水印
                PdfPageBase pb = pdf.Pages.Add(); //新增一页
                pdf.Pages.Remove(pb); //去除第一页水印

                var a = pdf.Pages.Count;

                int fromPage = 1;
                if (!string.IsNullOrEmpty(pageindex))
                {
                    fromPage = int.Parse(pageindex);
                }
                int toPage = a;
                if (!string.IsNullOrEmpty(pagesize))
                {
                    toPage = int.Parse(pagesize);
                }
                if (fromPage > a)
                {
                    fromPage = 1;
                }

                if (fromPage > 1 && toPage < a)
                {
                    for (int i = 0; i < (a - toPage); i++)
                    {
                        pdf.Pages.Remove(pdf.Pages[pdf.Pages.Count - 1]); //去掉后面的页数
                    }

                    for (int i = 1; i < fromPage; i++)
                    {
                        pdf.Pages.Remove(pdf.Pages[0]); //去掉前面的页数
                    }
                }
                else if (fromPage > 1)
                {
                    for (int i = 1; i < fromPage; i++)
                    {
                        pdf.Pages.Remove(pdf.Pages[0]); //去掉前面的页数
                    }
                }
                else if (toPage < a)
                {
                    for (int i = 0; i < (a - toPage); i++)
                    {
                        pdf.Pages.Remove(pdf.Pages[pdf.Pages.Count - 1]); //去掉后面的页数
                    }

                }

                var col = PdfBrushes.Blue;

                if (color == "Orange")
                {
                    col = PdfBrushes.Orange;
                }
                else if (color == "Olive")
                {
                    col = PdfBrushes.Olive;
                }
                else if (color == "Navy")
                {
                    col = PdfBrushes.Navy;
                }
                else if (color == "Moccasin")
                {
                    col = PdfBrushes.Moccasin;
                }
                else if (color == "MidnightBlue")
                {
                    col = PdfBrushes.MidnightBlue;
                }
                else if (color == "Lime")
                {
                    col = PdfBrushes.Lime;
                }
                else if (color == "Maroon")
                {
                    col = PdfBrushes.Maroon;
                }
                else if (color == "Magenta")
                {
                    col = PdfBrushes.Magenta;
                }
                else if (color == "PapayaWhip")
                {
                    col = PdfBrushes.PapayaWhip;
                }
                else if (color == "SteelBlue")
                {
                    col = PdfBrushes.SteelBlue;
                }
                else if (color == "White")
                {
                    col = PdfBrushes.White;
                }
                else if (color == "Yellow")
                {
                    col = PdfBrushes.Yellow;
                }
                else if (color == "Azure")
                {
                    col = PdfBrushes.Azure;
                }
                else if (color == "Black")
                {
                    col = PdfBrushes.Black;
                }
                else if (color == "Gold")
                {
                    col = PdfBrushes.Gold;
                }
                else if (color == "Green")
                {
                    col = PdfBrushes.Green;
                }
                else if (color == "Gray")
                {
                    col = PdfBrushes.Gray;
                }
                else if (color == "Ivory")
                {
                    col = PdfBrushes.Ivory;
                }
                else
                {
                    col = PdfBrushes.Blue;
                }


                PdfPageBase page = null;
                if (pdf.Pages.Count > 0)
                {
                    for (int i = 0; i < pdf.Pages.Count; i++)
                    {
                        page = pdf.Pages[i];
                        PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));
                        brush.Graphics.SetTransparency(0.3f);//设置透明度
                        brush.Graphics.Save();
                        brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);//设置平移变换
                        brush.Graphics.RotateTransform(jd);//设置角度
                        brush.Graphics.DrawString(marks, new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, dx), col, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
                        brush.Graphics.Restore();
                        brush.Graphics.SetTransparency(1);//设置透明度
                        page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
                    }
                    pdf.SaveToFile(targetPath);
                    return true;
                }
                return result;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #region 图片转PDF

        /// <summary>
        /// 图片转PDF
        /// </summary>
        /// <param name="jpgfile">图片本地地址</param>
        /// <param name="pdf">生成的文件路径和文件名</param>
        /// <returns></returns>
        public static bool ConvertJPG2PDF(string jpgfile, string pdf)
        {
            var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
            using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                try
                {
                    iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream);
                }
                catch (Exception ex)
                {
                }
                document.Open();
                using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var image = iTextSharp.text.Image.GetInstance(imageStream);
                    if (image.Height > iTextSharp.text.PageSize.A4.Height - 25)
                    {
                        image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                    }
                    else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
                    {

                        image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                    }
                    image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
                    document.Add(image);
                }
                document.Close();
            }
            return true;
        }

        /// <summary>
        /// 图片转pdf
        /// </summary>
        /// <param name="jpgfile">要转换的图片的路径,不需要加后缀和标识的数字</param>
        /// <param name="pdfoutputpath">转成后的文件地址和文件名</param>]
        /// <param name="count">图片的数量</param>
        public static void ImageToPDF(string jpgfile, string pdfoutputpath, int count)
        {

            var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
            using (var stream = new FileStream(pdfoutputpath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream);
                document.Open();
                for (int i = 1; i <= count; i++)
                {
                    using (var imageStream = new FileStream(jpgfile + i + ".jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var image = iTextSharp.text.Image.GetInstance(imageStream);
                        if (image.Height > iTextSharp.text.PageSize.A4.Height - 25)
                        {
                            image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                        }
                        else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
                        {
                            image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                        }
                        image.Alignment = iTextSharp.text.Element.ALIGN_MIDDLE;
                        document.NewPage();
                        document.Add(image);
                    }
                }
                document.Close();
            }
        }
        #endregion
    }
}

 

 

学习记录贴  有朋友发现任何不对的地方欢迎指出,有大佬有更简洁方便的方法也希望可以告诉我 欢迎评论

 

文章来源:https://www.cnblogs.com/kangsir7/p/15740557.html

版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
管理员
上一篇:ASP.Net 微信H5 OAuth2 认证 (前后端不分离)
下一篇:【OpenXml】Pptx的边框虚线转为WPF的边框虚线
评论列表

发表评论

评论内容
昵称:
验证码:
验证码
关联文章

.net 简单实现H5中将wordjpgpngPDFPDF添加水印并且控制样式编辑
Zookeeper 管理工具
C# 将PDF转为线性PDF
Asp.net 微信H5唤起支付支付回调
C# / VB.NET Word中嵌入多媒体(视频、音频)文件
C# 中使用JavaScriptPDF文档设置过期时间
软件:批量HEICJPG 苹果手机照片格式JPG
使用 .NET Core Quartz.NET 实现任务调度持久:更相信配置任务调度
DevExpress表格GridControl添加操作列单元格添加图片按钮并且实现点击链接URL跳浏览器
PNG-ICO图标格式互工具
AgileConfig-1.5.5 发布 - 支持 JSON 编辑模式
C# PNGICO,ICOPNG,PNG图标常规尺寸互
Epicor界面编辑状态控制
H5页面兼容苹果手机顶部刘海底部的安全黑条区域
C# 读取txt文件生成Word文档
C# PDF文档中应用多种不同字体
支付宝:H5 JSAPI支付开发手册
使用.NET 6开发TodoList应用(27)——实现API的Swagger文档
使用Hot Chocolate.NET 6构建GraphQL应用(3) —— 实现Query基础功能
C# 设置或验证 PDF中的文本域格式

热门标签
.NET Core .NET Reactor ag-grid AI发布 api安全 ASP.NET Core C#DLL加密 C#播放声音 C#代码混淆 C#代码加密 ChromeDriver Codex DateTime DBeaver devexpress devTool DLL混淆 edge.js EF EFCore Electron element-ui el-form el-table excel FastReport FileStream FolderBrowerDialog FolderSelectDialog form提交 git gridcontrol gridview input javascript json字符串 JS转换对象JSON jwt JWT授权 linq log Math MCP mitmproxy MVC MySQL Navicat netstat nginx node_modules NSwag Nuget Nuget镜像 number PowerShell pyinstaller python pythoncom python爬虫 python抓包 pywin32 redis Requests-html RestSharp Selenium sql SQL Server Swagger to-cms Visual Studio VSCode vue VueRouter vue路由 VUE页面通讯 Webpack Windows Windows服务 winform wmi xlrd yaml YESCMS YESWEB开发框架 白象 表单提交 播放声音 打开URL 代码混淆 弹窗提醒 端口占用 对象转换 分布式 公共字典 机器码 进程排查 静态资源 开发指南 路由参数 密钥 配置教程 配置文件 权限 人工智能 任务 任务调度 日期间隔 日志 日志记录 省市区 授权验证 数据库 四舍五入 文案 文件读取 文件夹选择 文件目录选择 问题排查 行政区域数据 页面通讯 中间件 CSharp 事务锁 工单系统 并发控制 重复提交 CMS Markdig Markdown markdown-it marked 技术选型 VS Code 开发工具 源代码管理 版本控制 Docker PostgreSQL 时区 部署排查 CMS架构 EF Core 主题系统 二次开发 插件系统 容器 运维命令 镜像清理 Linux NAS 远程挂载 飞牛 fnOS S/4HANA SAP GUI SAP HANA SAP R/3 SAP入门 SAP版本 ERP SAP SAP MM 库存管理 物料管理 采购管理 入门教程 SAP S/4HANA SPRO 企业结构 采购组织 MM01 物料主数据 物料类型 BP分组 业务伙伴 供应商主数据 ME41 RFQ 库存物料 采购流程 ME51 消耗性物料 科目分配 采购申请 AC03 ML81N 外部服务 服务主数据 Business Partner SAP培训 ME51N MM模块 Lean Services MM-SRV 外部服务采购 PIR 供应来源 采购主数据 采购信息记录 ME31K 框架协议 计划协议 采购合同 ME01 供应来源确定 货源清单 MEQ1 供应源确定 配额安排 配额评分 MD04 MD21 MRP 计划文件 需求计划 批量程序 MD01N MD02 MRP Live MD05 MM 物料计划 优化采购 供应源 采购订单 ME2A 供应商确认 采购监控 Flexible Workflow 凭证释放 采购审批 释放策略 实地盘点 物料凭证 货物移动 MIGO 收货 移动类型 已撤回 供应商退货 货物发出 STO 库存转储 转移过账 生产订单 预留 GR/IR MIRO 供应商发票 物流发票校验 OMR2 税码 FI PP SD 实操教程 MRBR OMR6 发票差异 交货成本 后续借记 MI01 实物盘点 盘点差异 公司代码 工厂 组织结构 OMS2 主数据定制 自动科目确定 BP角色 CVI 伙伴确定 编号范围 凭证类型 字段选择 FBN1 OMBT OMC2 会计凭证 OMJJ BOM 委外加工 项目类别L MRKO 供应商寄售 特殊库存K MRKON PIPE Pipeline 特殊库存P ERS MRIS 发票计划 周期性结算 里程碑付款 变更追踪 版本管理 采购凭证 SFTP WebDAV 网盘 飞牛fnOS AMPL HERS MPN 中文教程 库存确定 可用性检查 缺件检查 Output Management 消息确定 输出确定 分割评估 库存计价 评估类别 评估类型 PB00 RM0000 条件技术 采购定价 MM-FI集成 OBYC 库存估价 文本类型 文本采用 EFB EVO MSV SU3 用户参数 发票校验 合同参照 履约保留款 特别总账 预付款 Fiori Launchpad SAP Fiori 应用导航 用户体验 LSMW LTMC Migration Cockpit 数据迁移 BRFplus OPD Output Control My Inbox 审批流程 灵活工作流 SAP PP 外部加工 SAP QM 检验批 质量信息记录 采购收货 SAP PM 维护BOM 维护订单 SAP SD SAP Service 端到端流程 MM模块培训 FI-MM集成 供应商管理 审批配置 FICO入门 SAP FICO 财务配置 供应商税务 预扣税 House Bank 银行对账 客户清账 应收账款 FI控制 验证与替代 印度 GST 税务配置 F110 FBZP EWM入门 SAP EWM 仓库管理 OX14 成本核算 物料评估 后勤配置 物料组 价值更新 数量更新 PP-PI 流程制造 生产计划 容差配置 SAP事务码 SAP基础 TCODE Basis 事务代码 MMNR 编号区间 采购实操 组织架构 OMSF SAP实操 FI配置
联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码