主頁 > .NET開發 > .net 簡單實作在H5中將word、jpg、png轉成PDF給PDF添加水印并且控制樣式和可視化編輯

.net 簡單實作在H5中將word、jpg、png轉成PDF給PDF添加水印并且控制樣式和可視化編輯

2021-12-30 06:01:54 .NET開發

在寫完這三個需求之后 word轉PDF,PDF添加水印,并控制顯示的頁數,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 = "https://www.cnblogs.com/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 = "https://www.cnblogs.com/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
    }
}

 

 

學習記錄貼  有朋友發現任何不對的地方歡迎指出,有大佬有更簡潔方便的方法也希望可以告訴我 歡迎評論

 

本文來自博客園,作者:康Sir7,轉載請注明原文鏈接:https://www.cnblogs.com/kangsir7/p/15740557.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/397105.html

標籤:.NET技术

上一篇:使用.NET 6開發TodoList應用(11)——使用FluentValidation和MediatR實作介面請求驗證

下一篇:(原創)WinForm中莫名其妙的小BUG——RichTextBox自動選擇字詞問題

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more