My Task is to add User name to a fillable pdf (on the margin, not field) using C#. I tried to add a Text Annotation using a lot of Third Party dll like iTextSharp, spire.pdf....
However, whenever I add the text on the fillable pdf and save it, the fillable Fields disappear. Does anyone know how to complete this Task? Thanks.
seems to you use broken pdf file because of it is simple task.
I don't know how looks your code for tools you have tried. I use Apitron PDF Kit. Anyway I think it will look similarly for all tools.
Please see the following code:
using System;
using System.Collections.Generic;
using System.IO;
using Apitron.PDF.Kit.FixedLayout;
using Apitron.PDF.Kit.FixedLayout.Content;
using Apitron.PDF.Kit.FixedLayout.PageProperties;
using Apitron.PDF.Kit.Interactive.Annotations;
using Apitron.PDF.Kit.Interactive.Forms;
public void TestAcroForm_TextBlock()
{
using (Stream stream = new FileStream("filename.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (FixedDocument document = new FixedDocument())
{
Page page = document.Pages[0];
TextField textField = new TextField("UserName", "This is user name");
TextFieldView annotation = new TextFieldView(textField, new Boundary(100, 100, 300, 130));
document.AcroForm.Fields.Add(textField);
page.Annotations.Add(annotation);
using (Stream outStream = new FileStream("filename_out.pdf", FileMode.Create, FileAccess.ReadWrite))
{
document.Save(outStream);
}
}
}
}
Related
I want to convert an html string into a byte[] pdf and send it as a file for download. But all the libraries I see either have dependency issues or won't work and give errors like "System.Drawing.Common is not supported on this platform.".
I'm working on Ubuntu
Dotnet version 7.0.102
Some packages give warning like -
"Package 'PDFsharp 1.32.3057' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net7.0'. This package may not be fully compatible with your project."
this stops me from being able to use hot reload feature when using dotnet watch, it asks me to restart the server on every change.
You can use the iTextSharp library for this.
Please refer to the below code snippet for your reference :
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace HTMLToPDFExample
{
class Program
{
static void Main(string[] args)
{
// Your string HTML here
string html = #"<html><body>
<h1>Example HTML to PDF Conversion</h1>
<p>This is an example of how to convert an HTML string to a PDF document.</p>
</body></html>";
string pdfFile = "example.pdf";
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
using (var sr = new StringReader(html))
{
var htmlContext = new HTMLWorker(doc);
htmlContext.Parse(sr);
}
doc.Close();
}
}
File.WriteAllBytes(pdfFile, ms.ToArray());
}
}
}
}
I've a requirement like, there a file with name Log.txt and is a shared file using by two different libraries parent and child in parallel. In parent library we are adding some lines of data after that in child library deleting the same data in same file. But, we cannot close the FileStream in parent because it is keep on adding the data.
Parent code goes like below (Writing the data) :
using (FileStream fileStream = new FileStream(logFilePath, FileMode.Append))
{
using (StreamWriter log = new StreamWriter(fileStream))
{
log.WriteLine(strLog);
}
}
Child code goes like below (Clearing the data):
using (FileStream fileStream = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
//fileStream.SetLength(0);
using (StreamWriter log = new StreamWriter(fileStream))
{
File.WriteAllText(logFilePath, string.Empty);
}
}
Here I'm getting error This file is using by some other process. Yes, I know this error will come for which reason. My question is is there any other way to achieve this flow?
Thanks in advance
I am trying to include an xml file into a pdf/a2 using itext7 and c#.
The xml has to be included into pdf names tree.
I was finally able to do it, the xml stream seems to be in the right names tree position.
There is still a problem, the stream has suppose to be compressed but is not, viewing the output pdf in a notepad you see the plain text.
It seems that the itext7 PdfStream is not able to do it, or at least, I am not able to compress it even setting compressionleve=9 - stream.SetCompressionLevel(9) in my code.
Anyone has a clue on how to do it.
Thank you very much.
Mauro
Here is my code:
using iText.Forms;
using iText.Kernel.Pdf;
using iText.Pdfa;
using iText.Layout.Element;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace PdfXml
{
class Program
{
static void Main(string[] args)
{
string pdfIn = "\\xfar\\pdfin.pdf";
string pdfOut = "\\xfar\\pdfoutU.pdf";
string cdaIn = "\\xfar\\cda.xml";
StreamReader Reader = new StreamReader(cdaIn);
var content = new StringBuilder();
string line;
while (Reader.EndOfStream == false)
{
line = Reader.ReadLine();
content.AppendLine(line);
}
byte[] bytes = Encoding.ASCII.GetBytes(content.ToString());
PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdfIn), new PdfWriter(pdfOut));
PdfStream stream = new PdfStream();;
PdfNameTree nameTree1 = pdfDoc.GetCatalog().GetNameTree(new PdfName("XFAResource"));
stream.SetCompressionLevel(9);
stream.SetData(bytes, true);
stream.Put(PdfName.Filter, PdfName.FlateDecode);
nameTree1.AddEntry("dataset", stream);
nameTree1.BuildTree();
nameTree1.SetModified();
Console.WriteLine("ok");
}
pdfDoc.Close();
}
}
}
I am creating a pdf document using C# code in my process. I need to protect the docuemnt
with some standard password like "123456" or some account number. I need to do this without
any reference dlls like pdf writer.
I am generating the PDF file using SQL Reporting services reports.
Is there are easiest way.
I am creating a pdf document using C#
code in my process
Are you using some library to create this document? The pdf specification (8.6MB) is quite big and all tasks involving pdf manipulation could be difficult without using a third party library. Password protecting and encrypting your pdf files with the free and open source itextsharp library is quite easy:
using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);
}
It would be very difficult to do this without using a PDF library. Basically, you'll need to develop such library yourselves.
With help of a PDF library everything is much simpler. Here is a sample that shows how a document can easily be protected using Docotic.Pdf library:
public static void protectWithPassword(string input, string output)
{
using (PdfDocument doc = new PdfDocument(input))
{
// set owner password (a password required to change permissions)
doc.OwnerPassword = "pass";
// set empty user password (this will allow anyone to
// view document without need to enter password)
doc.UserPassword = "";
// setup encryption algorithm
doc.Encryption = PdfEncryptionAlgorithm.Aes128Bit;
// [optionally] setup permissions
doc.Permissions.CopyContents = false;
doc.Permissions.ExtractContents = false;
doc.Save(output);
}
}
Disclaimer: I work for the vendor of the library.
If anyone is looking for a IText7 reference.
private string password = "#d45235fewf";
private const string pdfFile = #"C:\Temp\Old.pdf";
private const string pdfFileOut = #"C:\Temp\New.pdf";
public void DecryptPdf()
{
//Set reader properties and password
ReaderProperties rp = new ReaderProperties();
rp.SetPassword(new System.Text.UTF8Encoding().GetBytes(password));
//Read the PDF and write to new pdf
using (PdfReader reader = new PdfReader(pdfFile, rp))
{
reader.SetUnethicalReading(true);
PdfDocument pdf = new PdfDocument(reader, new PdfWriter(pdfFileOut));
pdf.GetFirstPage(); // Get at the very least the first page
}
}
While using the itextsharp library for pdf generation, I came across this method:-
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(itextsharp.text.pdf.PdfTemplate);
Where, we can get Image instance from a PdfTemplate. But, I don't know how to create a PdfTemplate and there is no constructor taking a pdf file name or stream.
Why I want this is: I want to create an Image from a PDF file and then isert this image into another pdf file.
Anybody knows how to create PdfTemplate object ?
The PdfTemplate unfortunately isn't exactly what you think it is. iText and iTextSharp are PDF generators but not PDF renderers which is what you would need to convert a PDF to an image.
That said, you can still accomplish your goal, depending on the quality that you're looking for.
One of the more common uses of PdfTemplate is the subclass PdfImportedPage. If you create an Image from a PdfImportedPage you won't be creating a JPG or PNG or anything raster, you'll actually have a full version of your page wrapped up in an Image object. What this means is that you can apply transforms such as ScaleAbsolute() or whatever you want, but when you add it to the output PDF any text will still be true text (and thus selectable). This is the part where the quality comes in. If you start scaling the Image it will (mathematically) scale perfectly, but visually it might render imperfectly within something like Adobe Reader. If you zoom in it will be fine, but many screen programs don't render small type that well. Whether this is an issue for you or not I don't know.
Anyway, the code below is a full working sample targetting iTextSharp 5.1.1.0. It reads a page from an existing PDF, scales it by 50% and adds it to an output PDF.
using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//PDF file to pull the first page from
string inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Input.pdf");
//PDF file to output
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (Document doc = new Document())
{
using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
{
//Open our PDF for writing
doc.Open();
//We need a reader to pull pages from
PdfReader r = new PdfReader(inputFile);
//Get the first page of our source PDF
PdfImportedPage importedPage = w.GetImportedPage(r, 1);
//Insert a new page into our output PDF
doc.NewPage();
//Create an Image from the imported page
iTextSharp.text.Image Img = iTextSharp.text.Image.GetInstance(importedPage);
//Just to show why we are using an Image, scale the Image to 50% width and height of the original page
Img.ScaleAbsolute(importedPage.Width / 2, importedPage.Height / 2);
//Add the Image to the page
doc.Add(Img);
//Close our output PDF
doc.Close();
}
}
}
this.Close();
}
}
}