2020年6月30日 星期二

[研究][C#][ASP.NET]使用 Aspose.PDF v20.6.0 替換 .pdf 中文字

[研究][C#][ASP.NET]使用 Aspose.PDF  v20.6.0 替換 .pdf 中文字

2020-06-30

Visual Studio 2019 v16.6.2 + ASP.NET + WebForm + WebApplication
NuGet 安裝 Aspose.PDF v20.6.0


Evaluation Version Limitations
1. PDF created with an evaluation watermark
The evaluation version of Aspose.PDF for .NET provides full product functionality, but all the pages in the generated PDF documents are watermarked with "Evaluation Only. Created with Aspose.PDF. Copyright 2002-2016 Aspose Pty Ltd" at the top.

2.Limit of the Number of Collection Items that can be Processed
In the evaluation version, only four items can be processed from any collection (for example, only four pages, four form fields, etc.).

評估版產生的 .pdf 會有紅字
Evaluation Only. Created with Aspose.PDF. Copyright 2002-2020 Aspose Pty Ltd.

中文字問題

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PDFReplacebyAsposePDF.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
            <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" /><br />
        </div>
    </form>
</body>
</html>



Default.aspx.cs

using Aspose.Pdf;
using Aspose.Pdf.Text;
using System;
using System.IO;
using System.Text;

namespace PDFReplacebyAsposePDF
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        private static void SetLicense()
        {
            License license = new License();
            license.SetLicense(
               new MemoryStream(
                  EncryptDecryptLicense(File.ReadAllBytes(@"C:\Temp\pdflic.txt"), Encoding.UTF8.GetBytes("SYSVIN"))
               )
            );
        }
        private static byte[] EncryptDecryptLicense(byte[] licBytes, byte[] key)
        {
            byte[] output = new byte[licBytes.Length];
            for (int i = 0; i < licBytes.Length; i++) { output[i] = Convert.ToByte(licBytes[i] ^ key[i % key.Length]); }
            return output;
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            // For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
            // The path to the documents directory.
            //string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Open document
            //Document pdfDocument = new Document(dataDir + "ReplaceTextAll.pdf");
            Document pdfDocument = new Document(@"C:\Temp\template.pdf");

            // Create TextAbsorber object to find all instances of the input search phrase
            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("{$name}");

            // Accept the absorber for all the pages
            pdfDocument.Pages.Accept(textFragmentAbsorber);

            // Get the extracted text fragments
            TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;

            // Loop through the fragments
            foreach (TextFragment textFragment in textFragmentCollection)
            {
                // Update text and other properties
                textFragment.Text = "趙錢孫";
                //textFragment.TextState.Font = FontRepository.FindFont("Verdana");     // 中文字無法顯示
                //textFragment.TextState.Font = FontRepository.FindFont("微軟正黑體");   // 錯誤用法
                textFragment.TextState.Font = FontRepository.FindFont("DFKai-SB");  // 標楷體,請看 registry 中的值
                textFragment.TextState.FontSize = 22;
                //textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
                //textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green);
            }

            //dataDir = dataDir + "ReplaceTextAll_out.pdf";
            // Save resulting PDF document.
            pdfDocument.Save(@"C:\Temp\template3.pdf");
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            // For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
            // The path to the documents directory.
            //string dataDir = RunExamples.GetDataDir_AsposePdf_QuickStart();
            // Initialize license object

            Aspose.Pdf.License license = new Aspose.Pdf.License();

            // Set license
            //license.SetLicense("Aspose.Pdf.lic");
            //license.SetLicense(@"C:\Temp\pdflic.txt");
            //Console.WriteLine("License set successfully.");

            //FileStream myStream = new FileStream(@"C:\Temp\pdflic.txt", FileMode.Open);
            //// Set license
            //license.SetLicense(myStream);

            SetLicense();

            // For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
            // The path to the documents directory.
            //string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Open document
            //Document pdfDocument = new Document(dataDir + "ReplaceTextAll.pdf");
            Document pdfDocument = new Document(@"C:\Temp\template.pdf");

            // Create TextAbsorber object to find all instances of the input search phrase
            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("{$name}");

            // Accept the absorber for all the pages
            pdfDocument.Pages.Accept(textFragmentAbsorber);

            // Get the extracted text fragments
            TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;

            // Loop through the fragments
            foreach (TextFragment textFragment in textFragmentCollection)
            {
                // Update text and other properties
                textFragment.Text = "趙錢孫";
                //textFragment.TextState.Font = FontRepository.FindFont("Verdana");     // 中文字無法顯示
                //textFragment.TextState.Font = FontRepository.FindFont("微軟正黑體");   // 錯誤用法
                textFragment.TextState.Font = FontRepository.FindFont("DFKai-SB");  // 標楷體,請看 registry 中的值
                textFragment.TextState.FontSize = 22;
                //textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
                //textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green);
            }

            //dataDir = dataDir + "ReplaceTextAll_out.pdf";
            // Save resulting PDF document.
            pdfDocument.Save(@"C:\Temp\template3.pdf");
        }
    }
}

Button1 執行結果

(下圖) template.pdf 內容

(下圖) 取代後存檔結果


後來另外做了一個複雜的 .pdf 測試,文字依然可以順利替換掉。

********************************************************************************

(下圖) Button2 比 Button1 多處理授權問題,但是因為授權過期,無法執行。
https://docs.aspose.com/display/pdfnet/Licensing

註:Aspose.PDF 購買後是永久使用授權,但是只有一年更新,但授權檔案疑似要不斷下載更新,否則自己開發程式的若修改重新編譯,日期若比授權期限要新,就無法執行。(猜測)



(完)

沒有留言:

張貼留言