Filling XFA data to xfa form pdf with ITEXT 7 in C# - itext7

PdfReader reader = new PdfReader(sourceXfaPath);
PdfWriter writer = new PdfWriter(exportPdf);
PdfDocument pdfDoc = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
XfaForm xfa = form.GetXfaForm();
xfa.FillXfaForm(new FileStream(exportXfaXml,FileMode.Open));
xfa.Write(pdfDoc);
pdfDoc.Close();
reader.Close();
codes are above:
but it doesn't create pdf document, I'm not sure why it doesn't create it.
I just tried xfa.FillXfaForm(new FileStream(exportXfaXml,FileMode.Open)); to xfa.FillXfaForm(XmlReader.Create(path));
but it shows me same error

public void customGenerate(string sourceFilePath, string destinationtFilePath, string replacementXmlFilePath)
{
PdfReader pdfReader = new PdfReader(sourceFilePath);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms, '\0', true))
//using (PdfStamper stamper = new PdfStamper(pdfReader, ms))
{
XfaForm xfaForm = new XfaForm(pdfReader);
XmlDocument doc = new XmlDocument();
doc.Load(replacementXmlFilePath);
xfaForm.DomDocument = doc;
xfaForm.Changed = true;
XfaForm.SetXfa(xfaForm, stamper.Reader, stamper.Writer);
stamper.Close();
}
var bytes = ms.ToArray();
System.IO.File.WriteAllBytes(destinationtFilePath, bytes);
ms.Close();
}
pdfReader.Close();
}
This is my code to add Javacript to XFA PDF.
I'm going to add JavaScript[handle button , checkbox] to XFA pdf with avoid signature.

Related

How to download File from pdf which has its filepath in .NET Core API?

I am generating a PDF from HTML and I had some file which was added in PDF in this format:
BUT those link unable to download - I get an "Unauthorized" error...
My code:
if (DocumentAfter != null)
{
string documentAElement = "";
foreach (var item in DocumentAfter)
{
var path2 = FromEmaillID + item.FileName;
// var filePath2 = Path.Combine(Environment.WebRootPath, #"document", item.FileName);
documentAElement += "" + item.FileName + "<br />";
}
emailKeyValues.Add(EmailConstants.AfterDocuments, documentAElement);
}
In this code there are more than one file I am adding in an anchor tag and it will then assign to html with EmailConstants.AfterDocuments
And my pdf download code is
Byte[] bytes;
StringBuilder sb1 = new StringBuilder();
sb1.Append(emailMessage.Content);//Pass html string here
StringReader sr = new StringReader(sb1.ToString());
Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 25);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
//htmlparser.Parse(sr);
pdfDoc.Close();
bytes = memoryStream.ToArray();
memoryStream.Close();
//var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "yogTest.pdf");
System.IO.File.WriteAllBytes(filepath1, bytes);
}
This code is working properly as PDF is shown, but only the file which I am adding for downloading is not working?

Cannot save pdf file on my phone or bluestacks Xamarin.Forms

i'm trying to create a pdf using PdfSharpCore for Xamarin Forms but I've run into some issues.
private void CreatePdf(object sender)
{
PdfDocument pdf = new PdfDocument();
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
graph.DrawString("This is my first PDF document", font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string localFilename = "test.pdf";
string localPath = Path.Combine(documentsPath, localFilename);
MemoryStream stream = new MemoryStream();
pdf.Save(stream, false);
byte[] bytes = stream.ToArray();
File.WriteAllBytes(localPath, bytes);
}
This is my function that generate the pdf and save it but when I press the button that invoke it, nothing happens.
I've already add the the permissions on the AndroidManifest.xml file like this:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I've tried using a library called Xamarin.Forms.SaveOpenPDFPackage. With this library you can
save and open your brand new pdf by doing this:
await CrossXamarinFormsSaveOpenPDFPackage.Current.SaveAndView("myFile1.pdf", "application/pdf", stream, PDFOpenContext.InApp);
It half works: it opens my new pdf but it doesn't save it.
Do you have any tip?
You could try to use Syncfusion.Xamarin.PDF.
Install from NuGet package first.
Creating a PDF document with table:
//Create a new PDF document.
PdfDocument doc = new PdfDocument();
//Add a page.
PdfPage page = doc.Pages.Add();
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
//Add values to list
List<object> data = new List<object>();
Object row1 = new { ID = "E01", Name = "Clay" };
Object row2 = new { ID = "E02", Name = "Thomas" };
Object row3 = new { ID = "E03", Name = "Andrew" };
Object row4 = new { ID = "E04", Name = "Paul" };
Object row5 = new { ID = "E05", Name = "Gray" };
data.Add(row1);
data.Add(row2);
data.Add(row3);
data.Add(row4);
data.Add(row5);
//Add list to IEnumerable
IEnumerable<object> dataTable = data;
//Assign data source.
pdfGrid.DataSource = dataTable;
//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new PointF(10, 10));
//Save the PDF document to stream.
MemoryStream stream = new MemoryStream();
doc.Save(stream);
//Close the document.
doc.Close(true);
//Save the stream as a file in the device and invoke it for viewing
Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("Output.pdf", "application/pdf", stream);
For more details about the ISave, you could get the whole code from Syncfusion official document.

iText7 how to add another pdf as background to exising pdf

I have 2 PDF files. under is single-page PDF file and must be a background for every page of original...
This is not working
public static byte[] overlay(byte[] original, byte[] under)
{
using (var resultStream = new MemoryStream())
{
var pdfWriter = new PdfWriter(resultStream);
var pdfReader = new PdfReader(new MemoryStream(original));
var pdfDoc = new PdfDocument(pdfReader, pdfWriter);
for (var p = 1; p <= pdfDoc.GetNumberOfPages(); p++)
{
var pdfUnder = new PdfDocument(new PdfReader(new MemoryStream(under)));
var pdfUnderPage = pdfUnder.GetFirstPage().CopyAsFormXObject(pdfDoc);
var page = pdfDoc.GetPage(p);
var canvas = new PdfCanvas(page.NewContentStreamBefore(),
page.GetResources(), pdfDoc);
canvas.AddXObjectAt(pdfUnderPage, 0, 0);
pdfUnder.Close();
}
pdfDoc.Close();
return resultStream.ToArray();
}
}

Insert an image into an existing pdf document using iText Sharp

I need to insert an image into an existing pdf at a specific location. I tried the answer at this question. But whatever different ways I do the image is being inserted at (0,0) position (bottom left corner). I tried another approach where instead of using stream I used Document class in iTextSharp as shown here. Now I am able to place the image at the desired position but this method is creating a new document with just this image. Most of the articles I searched are using PdfReader and PdfStamper so I think this is the recommended way. Any help is appreciated. Posting below code for both the methods I tried.
PdfStamper method
private void AddImage(string filePath)
{
string imageURL = #"ImagePath\Image.jpg";
using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
using (Stream outputPdfStream = new FileStream(#"ResultingPdfPath\Abcd.pdf", FileMode.Create, FileAccess.ReadWrite))
{
Image image = Image.GetInstance(inputImageStream);
image.ScaleToFit(100, 100);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
PdfContentByte content = stamper.GetUnderContent(1);
image.SetAbsolutePosition(100f, 150f);
content.AddImage(image);
stamper.Close();
reader.Close();
}
}
Document class method
private void TestMessage(string filePath)
{
string imageURL = #"ImagePath\Image.jpg";
Document doc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Open));
doc.Open();
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
jpg.ScaleToFit(140f, 120f);
jpg.SetAbsolutePosition(100, 100);
jpg.SpacingBefore = 10f;
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_LEFT;
doc.Add(jpg);
doc.Close();
}
Let me know if you need further information.
I adapted your method to accept variable out paths and positions and tested it with iTextSharp 5.5.7 like this:
[TestFixture]
class TestInsertImage
{
/// iText stamp image on top not always working
/// http://stackoverflow.com/questions/33898280/itext-stamp-image-on-top-not-always-working
///
[Test]
public void AddStampToTestPdf()
{
Directory.CreateDirectory(#"C:\Temp\test-results\content\");
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);
}
private void AddImage(string filePath, string outPath, float x, float y)
{
string imageURL = #"c:\Repo\GitHub\testarea\itext5\src\test\resources\mkl\testarea\itext5\layer\Willi-1.jpg";
using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
using (Stream outputPdfStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
{
Image image = Image.GetInstance(inputImageStream);
image.ScaleToFit(100, 100);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
PdfContentByte content = stamper.GetUnderContent(1);
image.SetAbsolutePosition(x, y);
content.AddImage(image);
stamper.Close();
reader.Close();
}
}
}
The results are included below.
As you see, the positioning information clearly are respected, and the image is definitely not always at the bottom left corner.
If this indeed does not work for the OP, he is keeping information from us required to help him.
Multipage-stamp-Image-100-150.pdf
Created using
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);
Multipage-stamp-Image-150-100.pdf
Created using:
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);

.net mvc3 iTextSharp how to add image to pdf in memory stream and return to browser

I have a .pdf file stored in my database, and I have a signature file (.png) stored in my database. I am trying to use iTextSharp to add the signature image to the .pdf file, and display the result to the browser.
Here is my code:
byte[] file = Repo.GetDocumentBytes(applicantApplication.ApplicationID, documentID);
byte[] signatureBytes = Repo.GetSignatureBytes((Guid)applicantApplicationID, signatureID);
iTextSharp.text.Image signatureImage = iTextSharp.text.Image.GetInstance(signatureBytes);
iTextSharp.text.Document document = new iTextSharp.text.Document();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(file, 0, file.Length, true, true))
{
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
signatureImage.SetAbsolutePosition(200, 200);
signatureImage.ScaleAbsolute(200, 50);
document.Add(signatureImage);
document.Close();
return File(ms.GetBuffer(), "application/pdf");
}
The page loads, and there is a .pdf with a signature, but the original document is nowhere to be found. It looks like I'm creating a new .pdf file and putting the image in there instead of editing the old .pdf file.
I have verified that the original .pdf document is being loaded into the "file" variable. I have also verified that the length of the MemoryStream "ms" is the same as the length of the byte[] "file".
I ended up doing something like this in my repository:
using (Stream inputPdfStream = new MemoryStream(file, 0, file.Length, true, true))
using (Stream inputImageStream = new MemoryStream(signatureBytes, 0, signatureBytes.Length, true, true))
using (MemoryStream outputPdfStream = new MemoryStream())
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var cb = stamper.GetOverContent(1);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(400, 100);
image.ScaleAbsolute(200, 50);
cb.AddImage(image);
stamper.Close();
return outputPdfStream.GetBuffer();
}
I adapted it from a few other answers on StackOverflow

Resources