private void btnProtPdf_Click(object sender, EventArgs e) { if (ofdAbrirArquivo.ShowDialog() == DialogResult.OK) { using (PDFDoc doc = new PDFDoc(ofdAbrirArquivo.FileName)) { //Apply a new security handler with given security settings. // In order to open saved PDF you will need a user password 'test'. SecurityHandler new_handler = new SecurityHandler(SecurityHandler.AlgorithmType.e_AES_256); // Set a new password required to open a document string my_password = "******"; new_handler.ChangeUserPassword(my_password); // Set Permissions new_handler.SetPermission(SecurityHandler.Permission.e_print, true); new_handler.SetPermission(SecurityHandler.Permission.e_extract_content, false); // Note: document takes the ownership of new_handler. doc.SetSecurityHandler(new_handler); doc.Save(GetNewFileName(ofdAbrirArquivo.FileName, FileNameOptionEnum.Encrypt), SDFDoc.SaveOptions.e_linearized); } } }
public FileItemDTO ProtectFile(FileItemEntity fileItem) { fileItem.FileFullPath = FileUtils.GetDefaultInputPath() + fileItem.FileName; File.WriteAllBytes(fileItem.FileFullPath, fileItem.Bytes); var fileItemDTO = new FileItemDTO() { Id = fileItem.Id, FileFullPath = FileUtils.GetNewFileName(fileItem.FileName, FileNameOptionEnum.Protect) }; fileItemDTO.FileName = FileUtils.GetSafeFileName(fileItemDTO.FileFullPath); using (PDFDoc doc = new PDFDoc(fileItem.FileFullPath)) { SecurityHandler new_handler = new SecurityHandler(SecurityHandler.AlgorithmType.e_AES_256); string my_password = "******"; new_handler.ChangeUserPassword(my_password); new_handler.SetPermission(SecurityHandler.Permission.e_print, true); new_handler.SetPermission(SecurityHandler.Permission.e_extract_content, false); doc.SetSecurityHandler(new_handler); doc.Save(fileItemDTO.FileFullPath, SDFDoc.SaveOptions.e_linearized); } return(fileItemDTO); }
/// <summary> /// Genera la factura de la reserva id pasada como parametro, si la factura pertenece al socio y si ha pagado la reserva, y la devuelve al socio /// </summary> /// <param name="id">id de la reserva para la cual mostrar la factura</param> /// <returns>pdf con la factura si socio, sino redirige a /Home/index o /Admin/index dependiendo si es admin o no logueado</returns> public ActionResult VerFacturaReserva(int? id) { if (isSocio()) { reservas reserva = db.reservas.Find(id); if (reserva == null) { addError("No tiene permisos para visualizar esta reserva"); saveErrors(); return RedirectToAction("MisReservas", "Socio"); } string socio_id = (string)Session["UserID"]; if (reserva.socios.id != socio_id) { addError("No tiene permisos para visualizar esta reserva"); saveErrors(); return RedirectToAction("MisReservas", "Socio"); } if (reserva.pagado == false) { addError("La factura no puede ser visualizada hasta que la reserva sea abonada"); saveErrors(); return RedirectToAction("MisReservas", "Socio"); } // Creacion del pdf a partir de los datos xml en la BBDD PDFNet.Initialize(); // Ruta relavita a las carpetas que contienen los archivos string input_path = "c:/Google Drive/PFC/pdf/"; string output_path = "c:/Google Drive/PFC/pdf/Output/"; try { // Juntar XFDF desde el xml string PDFDoc in_doc = new PDFDoc(input_path + "factura.pdf"); { in_doc.InitSecurityHandler(); //Debug.WriteLine("Juntamos XFDF string con el PDF..."); //reservas reserva = db.reservas.Find(id); string str = reserva.facturas.xml_factura; //Debug.WriteLine(str); using (FDFDoc fdoc = new FDFDoc(FDFDoc.CreateFromXFDF(str))) { in_doc.FDFMerge(fdoc); // Iniciamos los permisos del pdf, para que no se pueda editar StdSecurityHandler newHandler = new StdSecurityHandler(); newHandler.SetPermission(SecurityHandler.Permission.e_doc_modify, false); newHandler.SetPermission(SecurityHandler.Permission.e_fill_forms, false); newHandler.SetPermission(SecurityHandler.Permission.e_extract_content, false); newHandler.SetPermission(SecurityHandler.Permission.e_mod_annot, false); in_doc.SetSecurityHandler(newHandler); in_doc.Save(output_path + "factura_modificada.pdf", SDFDoc.SaveOptions.e_linearized); Debug.WriteLine("Juntado completado."); } } } catch (PDFNetException e) { Debug.WriteLine(e.Message); } return File("c:/Google drive/PFC/pdf/output/factura_modificada.pdf", "application/pdf"); } else return RedirectToAction("Index", isAdmin() ? "Admin" : "Home"); }
static void Main(string[] args) { PDFNet.Initialize(); // Relative path to the folder containing test files. string input_path = "../../TestFiles/"; string output_path = "../../TestFiles/Output/"; // Example 1: Securing a document with password protection and adjusting permissions // on the document. try { // Open the test file Console.WriteLine("-------------------------------------------------"); Console.WriteLine("Securing an existing document..."); using (PDFDoc doc = new PDFDoc(input_path + "fish.pdf")) { if (!doc.InitSecurityHandler()) { Console.WriteLine("Document authentication error..."); return; } // Perform some operation on the document. In this case we use low level SDF API // to replace the content stream of the first page with contents of file 'my_stream.txt' if (true) // Optional { Console.WriteLine("Replacing the content stream, use flate compression..."); // Get the first page dictionary using the following path: trailer/Root/Pages/Kids/0 Obj page_dict = doc.GetTrailer().Get("Root").Value(). Get("Pages").Value().Get("Kids").Value().GetAt(0); // Embed a custom stream (file mystream.txt) using Flate compression. MappedFile embed_file = new MappedFile(input_path + "my_stream.txt"); FilterReader mystm = new FilterReader(embed_file); page_dict.Put("Contents", doc.CreateIndirectStream(mystm)); embed_file.Close(); } // Apply a new security handler with given security settings. // In order to open saved PDF you will need a user password 'test'. SecurityHandler new_handler = new SecurityHandler(); // Set a new password required to open a document string my_password = "******"; new_handler.ChangeUserPassword(my_password); // Set Permissions new_handler.SetPermission(SecurityHandler.Permission.e_print, true); new_handler.SetPermission(SecurityHandler.Permission.e_extract_content, false); // Note: document takes the ownership of new_handler. doc.SetSecurityHandler(new_handler); // Save the changes. Console.WriteLine("Saving modified file..."); doc.Save(output_path + "secured.pdf", 0); } Console.WriteLine("Done. Result saved in secured.pdf"); } catch (PDFNetException e) { Console.WriteLine(e.Message); } // Example 2: Reading password protected document without user feedback. try { // In this sample case we will open an encrypted document that // requires a user password in order to access the content. Console.WriteLine("-------------------------------------------------"); Console.WriteLine("Open the password protected document from the first example..."); using (PDFDoc doc = new PDFDoc(output_path + "secured.pdf")) // Open the encrypted document that we saved in the first example. { Console.WriteLine("Initializing security handler without any user interaction..."); // At this point MySecurityHandler callbacks will be invoked. // MySecurityHandler.GetAuthorizationData() should collect the password and // AuthorizeFailed() is called if user repeatedly enters a wrong password. if (!doc.InitStdSecurityHandler("test")) { Console.WriteLine("Document authentication error..."); Console.WriteLine("The password is not valid."); return; } else { Console.WriteLine("The password is correct! Document can now be used for reading and editing"); // Remove the password security and save the changes to a new file. doc.RemoveSecurity(); doc.Save(output_path + "secured_nomore1.pdf", 0); Console.WriteLine("Done. Result saved in secured_nomore1.pdf"); } } } catch (PDFNetException e) { Console.WriteLine(e.Message); } Console.WriteLine("Tests completed."); }