1.download iTextSharp.dll,Please find it by yourself
At VS2012 or other version:
2.import iTextSharp to reference
3.using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
4.At Button Event:
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
//openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string filename = Path.GetFileName(openFileDialog1.FileName);
if ((myStream = openFileDialog1.OpenFile()) != null)
{
textBox1.Text = filename;
string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string InputFile = Path.Combine(WorkingFolder, "xx.pdf");
string OutputFile = Path.Combine(WorkingFolder, "xx_enc.pdf");
using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
沒有留言:
張貼留言