How to insert barcode into PDF created by IText7 HtmlConverter.ConvertToDocument method - c#

I'm using IText 7 to convert my HTML file into PDF and auto download the file when users click a button.
Currently I'm planning to insert a barcode using IText7 into the PDF file, however I encountered some error. Btw, it works fine without the 'barcode code'.
This is the error : 'iText.Kernel.PdfException: 'Pdf indirect object belongs to other PDF document. Copy object to current pdf document.''
How can I add a barcode at the end of my pdf file?
public MemoryStream GetCovidFormPdfByAccessionNumber(string htmlFile, string accessionNumber)
{
var workStream = new MemoryStream();
using (var pdfWriter = new PdfWriter(workStream))
{
pdfWriter.SetCloseStream(false);
var pdfDoc = new PdfDocument(pdfWriter);
using (var document = HtmlConverter.ConvertToDocument(htmlFile, pdfWriter))
{
document.Add(CreateBarcode(accessionNumber, pdfDoc));
}
}
workStream.Position = 0;
return workStream;
}
private static Image CreateBarcode(string code, PdfDocument pdfDoc)
{
Barcode39 barcode = new Barcode39(pdfDoc);
barcode.SetCode(code);
//Create barcode object to put it to the cell as image
PdfFormXObject barcodeObject = barcode.CreateFormXObject(ColorConstants.BLACK, ColorConstants.BLACK, pdfDoc);
var image = new Image(barcodeObject);
image.SetWidth(250);
return image;
}

Related

Itext PDF Image

I am trying to add a signature to the 2nd page of a PDF Form. The PDF was created outside of IText, but it has fields that were populated using IText in C#/MVC. That part works fine.
The issue is getting the signature image to the 2nd page. I can get the image onto the 1st page and position it, but cannot get it to the 2nd page.
I have tried to using the var PdfDocument class' GetPage(x) method without any luck. I have also tried to use GetLastPage(). No luck.
I tried the above approach before flattening the fields and after but no luck.
PdfReader reader = new PdfReader(fileSource);
System.IO.MemoryStream m = new System.IO.MemoryStream();
PdfWriter writer = new PdfWriter(m);
PdfDocument pdf = new PdfDocument(reader, writer);
Document document = new Document(pdf);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
String imageFile = "C:/Temp/signature.png";
ImageData data = ImageDataFactory.Create(imageFile);
Image img = new Image(data);
img.SetFixedPosition(50, 50);
pdf.GetPage(2);
document.Add(img);
form.FlattenFields();
document.Close();
pdf.Close();
pdfBytes = m.ToArray();
return new FileContentResult(pdfBytes, "application/pdf");
Any help would be appreciated.

How to dispose/close/release iText 7's control of newly created pdfs

I can create multiple pdf documents using iText 7. However, after creation I want to send an email with the newly created pdfs as attachments. This results in sharing violation error. See my steps below.
First I have a static class to initialize pdfs called PDFLibrary:
public static PdfWriter CreateWriter(string Filepath)
{
//set writer properties
WriterProperties writerProperties = new WriterProperties();
writerProperties.SetStandardEncryption(Encoding.ASCII.GetBytes(""), Encoding.ASCII.GetBytes("password"), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128);
PdfWriter writer = new PdfWriter(Filepath, writerProperties);
//set compression level
writer.SetCompressionLevel(9); //0 = best speed, 9 = best compression, -1 is default
return writer;
}
public static PdfDocument CreatePDFDocument(PdfWriter Writer)
{
return new PdfDocument(Writer);
}
public static Document CreateDocument(PdfDocument PDFDoc)
{
Document document = new Document(PDFDoc);
document.SetMargins(25,25,25,25);
return document;
}
Then I reference the above class and methods:
PdfWriter writer;
PdfDocument pdfDocument;
Document doc;
private void CreatePDFs(string PDFPath)
{
writer = PDFLibrary.CreateWriter(PDFPath);
pdfDocument = PDFLibrary.CreatePDFDocument(writer);
doc = PDFLibrary.CreateDocument(pdfDocument);
}
Finally (after adding tables and cells to create the desired pdfs), I close the pdf objects:
private void CloseDocumentStreams()
{
doc.Close();
writer.SetCloseStream(true);
writer.Close();
}
Now attempting the following operation in a send email method results in an "IOException: Sharing violation on path":
Attachment attachment = new Attachment(pathToPDF[i]);
Is there a way to fully release iText's handle over the documents? The example documentation only shows document.Close() where document is type Document.

Can I attach an image to a signed pdf document using itext 7?

I have attached an image into a signed pdf document using itext7, but the signature became invalid. Is there any solution for this
string source = #"D:\SampleProjects\itext\file\test.pdf";
string target = #"D:\SampleProjects\itext\file\tests.pdf";
string img = #"D:\SampleProjects\itext\file\sign_valid.png";
PdfDocument pdfDocument = new PdfDocument(new PdfReader(source), new PdfWriter(target));
// Document to add layout elements: paragraphs, images etc
Document document = new Document(pdfDocument);
var noofpages = pdfDocument.GetNumberOfPages();
// Load image from disk
ImageData imageData = ImageDataFactory.Create(img);
// Create layout image object and provide parameters. Page number = 1
Image image = new Image(imageData).ScaleAbsolute(100, 100).SetFixedPosition(1, 25, 25);
document.Add(image);
document.Close();
It's a feature that the signature becomes invalid when the document is changed.
So I would say the answer to your question is no.
I recommend you attach the image before the document is signed.

ITextSharp pdf resize and data alignment

I am using ITextSharp to convert HTML to PDF but i want the PDF to be generated of size 5cm width. I used the following code
var pgSize = new iTextSharp.text.Rectangle(2.05f, 2.05f);
Document doc = new Document(pgSize);
but it is just resizing the pdf and my data disappeared in the pdf or get hide.
How can i align the data in the center in PDF or resize the pdf? Here is my code
public void ConvertHTMLToPDF(string HTMLCode)
{
try
{
System.IO.StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
StringReader reader = new StringReader(HTMLCode);
var pgSize = new iTextSharp.text.Rectangle(2.05f, 2.05f);
Document doc = new Document(pgSize);
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~") + "/App_Data/HTMLToPDF.pdf",
FileMode.Create));
doc.Open();
foreach (IElement element in HTMLWorker.ParseToList(
new StringReader(HTMLCode), null))
{
doc.Add(element);
}
doc.Close();
Response.End();
}
catch (Exception ex)
{
}
}
You are creating a PDF that measures 0.0723 cm by 0.0723 cm. That is much too small to add any content. If you want to create a PDF of 5 cm by 5 cm, you need to create your document like this:
var pgSize = new iTextSharp.text.Rectangle(141.732f, 141.732f);
Document doc = new Document(pgSize);
As for the alignment, that should be defined in the HTML, but you are using an old version of iText and you are using the deprecated HTMLWorker.
You should upgrade to iText 7 and pdfHTML as described here: Converting HTML to PDF using iText
Also: the size of the page can be defined in the #page-rule of the CSS. See Huge white space after header in PDF using Flying Saucer
Why would you make it difficult for yourself by using an old iText version, when the new version allows you to do this:
#page {
size: 5cm 5cm;
}

How to show PDF file in MigraDoc.Rendering.Forms.DocumentPreview (in WinForms)?

I have a simple questions. How can you show a PDf file by using PagePreview?
I have a full pathname document.FileName = "c:\scans\Insurance_34345.pdf";
pagePreview.Preview(document.FileName); or something...
If there another way for showing a pdf. It's okay. I want to show it on a WinForms Form.
I tried this. I don't know what I have to do...
in the Designer
private MigraDoc.Rendering.Forms.DocumentPreview dpvScannedDoc;
Part of the code
string fullPadnaam = Path.Combine(defaultPath, document.FileName);
//PdfDocument pdfDocument = new PdfDocument(fullPadnaam);
//PdfPage page = new PdfPage(pdfDocument);
//XGraphics gfx = XGraphics.FromPdfPage(page);
MigraDoc.DocumentObjectModel.Document pdfDocument = new MigraDoc.DocumentObjectModel.Document();
pdfDocument.ImagePath = fullPadnaam;
var docRenderer = new DocumentRenderer(pdfDocument);
docRenderer.PrepareDocument();
var inPdfDoc = PdfReader.Open(fullPadnaam, PdfDocumentOpenMode.ReadOnly);
for (var i = 0; i < inPdfDoc.PageCount; i++)
{
pdfDocument.AddSection();
docRenderer.PrepareDocument();
var page = inPdfDoc.Pages[i];
var gfx = XGraphics.FromPdfPage(page);
docRenderer.RenderPage(gfx, i + 1);
}
var renderer = new PdfDocumentRenderer();
renderer.Document = pdfDocument;
renderer.RenderDocument();
// MigraDoc.DocumentObjectModel.IO.DdlWriter dw = new MigraDoc.DocumentObjectModel.IO.DdlWriter("HelloWorld.mdddl");
// dw.WriteDocument(pdfDocument);
// dw.Close();
//renderer.PdfDocument.rea(outFilePath);
//string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document1);
dpvScannedDoc.Show( pdfDocument);
PDFsharp does not render PDF files. You cannot show PDF files using the PagePreview.
If you use the XGraphics class for drawing then you can use shared code that draws on the PagePreview and on PDF pages.
The PagePreview sample can be found in the sample package and here:
http://www.pdfsharp.net/wiki/Preview-sample.ashx
If you have code that creates a new PDF file using PDFsharp then you can use the PagePreview to show on screen what you would otherwise draw on PDF pages. You cannot draw existing PDF pages using the PagePreview because PDF does not render PDF.
The MigraDoc DocumentPreview can display MDDDL files (your sample code creates a file "HelloWorld.mdddl"), but it cannot display PDF files.
If the MDDDL uses PDF files as images, they will not show up in the preview. They will show when creating a PDF from the MDDDL.

Categories