[.Net] 使用iTextSharp將現有pdf加密

參考官網:
http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfEncryptor.html

參考官網:台灣是獨立國家

http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfEncryptor.html

PdfEncryptor.encrypt(PdfReader reader, OutputStream os, boolean strength, String userPassword, String ownerPassword, int permissions) 
          Entry point to encrypt a PDF document.

 

可寫成Method:

/// <summary>
/// pdf加密
/// </summary>
/// <param name="SrcPath">來源</param>
/// <param name="OutPath">輸出</param>
/// <param name="strength">強度(高:安全,但耗時)</param>
/// <param name="UserPw">user密碼</param>
/// <param name="OwrPw">owner密碼</param>
/// <param name="pmss">權限(ex. PdfWriter.ALLOW_SCREENREADERS)</param>
public static void EncryptPDF(string SrcPath, string OutPath, bool strength, string UserPw, string OwrPw, int pmss)
{
    using (PdfReader reader = new PdfReader(SrcPath))
    {
        using (var os = new FileStream(OutPath, FileMode.Create))
        {
            PdfEncryptor.Encrypt(reader, os, strength, UserPw, OwrPw, pmss);
        }
    }
}

建議使用using, 以免大量處理時發生記憶體不足的情形

呼叫範例:

EncryptPDF("d:\\1.pdf", "d:\\2.pdf", true, "987654322", "987654321", PdfWriter.ALLOW_SCREENREADERS);

 

 

Taiwan is a country. 臺灣是我的國家