0
我使用ASP.NET創建了一個簡單的PDF創建器應用程序。該應用程序將使用密碼即時創建PDF文件以保護該文檔。這裏是我的代碼:如何在不下載PDF文件的情況下使用ITextSharp在PDF文件上設置密碼?
Sub createPDFFile()
Dim doc As Document = New Document
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"pdf\result.pdf", FileMode.Create))
doc.Open()
doc.Add(New Paragraph("Hello World!! only Testing"))
doc.Close()
SetPDFPassword(Server.MapPath("~/pdf/result.pdf"), "resultwithpassword.pdf", "12345")
Response.Redirect("pdf/1.pdf")
End Sub
,這裏是我的PDF文件添加密碼,代碼:
Private Sub SetPDFPassword(ByVal FullPathPdfFileName As String, ByVal DownloadPDFFileName As String, ByVal ForOpenPassword As String)
Dim sname As String = FullPathPdfFileName
Dim sname1 As String = New System.IO.FileInfo(FullPathPdfFileName).DirectoryName & "/test.pdf"
Dim reader As New PdfReader(sname)
Dim n As Integer = reader.NumberOfPages
Dim document As New Document(reader.GetPageSizeWithRotation(1))
Dim writer As PdfWriter = PdfWriter.GetInstance(document, New IO.FileStream(sname1, IO.FileMode.Create))
writer.SetEncryption(PdfWriter.STRENGTH128BITS, ForOpenPassword, Nothing, PdfWriter.AllowPrinting)
document.Open()
Dim cb As PdfContentByte = writer.DirectContent
Dim page As PdfImportedPage
Dim rotation As Integer
Dim i As Integer = 0
While i < n
i += 1
document.SetPageSize(reader.GetPageSizeWithRotation(i))
document.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 OrElse rotation = 270 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, _
reader.GetPageSizeWithRotation(i).Height)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, _
0)
End If
End While
document.Close()
writer.Close()
Dim PDFfile As New IO.FileStream(sname1, IO.FileMode.Open)
Dim FileSize As Long
FileSize = PDFfile.Length
Dim buffer As Byte() = New Byte(CInt(FileSize) - 1) {}
PDFfile.Read(buffer, 0, CInt(FileSize))
PDFfile.Close()
System.IO.File.Delete(sname1)
Response.AddHeader("Content-Disposition", "attachment;filename=" & DownloadPDFFileName)
Response.ContentType = "application/pdf"
Response.BinaryWrite(buffer)
Response.Flush()
Response.Close()
End Sub
代碼是完美。它可以生成PDF文件並添加一些密碼來打開,但PDF文件將發送給用戶。有誰知道如何生成帶有密碼的PDF文件,但結果文件仍在服務器上,只能從網頁瀏覽器顯示(不顯示下載提示)?在此先感謝..:D