Multiple PDF From Original PDF using iTextSharp - itext

I'm using iTextSharp to create an invoice in PDF.
Now I need to create multiple copies of that PDF, adding headers such as "DUPLICATE", "TRIPLICATE", and so on.
Is that possible?
Document pdfDoc = new Document(PageSize.A4, 20, 25, 25, 10);
System.IO.FileStream file = new System.IO.FileStream(Server.MapPath("~/" + fileUploadLoc + "/" + "File.pdf", System.IO.FileMode.OpenOrCreate);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, file);
fileName = Convert.ToString("Invoice.pdf");
pdfDoc.Open();
pdfWriter.Open();
PdfPTable nested = new PdfPTable(1);
nested.DefaultCell.Border = Rectangle.BOX;
nested.WidthPercentage = 100;
PdfPCell Tableheader = new PdfPCell(new Phrase("Company Name", titleHeaderFont));
Tableheader.HorizontalAlignment = 1;
Tableheader.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;
Tableheader.Left = 45f;
Tableheader.Right = 45f;
table.AddCell(Tableheader);
PdfPCell Tableheader7 = new PdfPCell(new Phrase("Triplicate for Supplier", fontsize7normaol));
////Above line has to be changed in each new pdf
Tableheader7.HorizontalAlignment = 1;
Tableheader7.Border = Rectangle.LEFT_BORDER |
Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER |
Rectangle.TOP_BORDER;
Tableheader7.Right = 25f;
nested1.AddCell(Tableheader7);
pdfDoc.Add(table);
pdfWriter.CloseStream = false;
pdfDoc.Close();

Related

Field validation in editable pdf while filling data

I have editable pdf with fields name, roll number , DOB and city, I want to validate the fields like, for example when I enter the value in roll number field, if name is empty then it should alert "name is empty" and similar to roll number and DOB and city.
DOB - Need to validate mm/dd/yyyy format.
I am able to get fields and values using below iTextSharp code, but how can validate and and show alert to user.
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(filename);
using (MemoryStream outputStream = new MemoryStream())
{
//PdfStamper stamper = new PdfStamper(reader, );
using (PdfStamper stamper = new PdfStamper(reader, outputStream, '\0', true))
{
PdfWriter writer = stamper.Writer;
AcroFields acroFields = reader.AcroFields;
AcroFields.Item dateField = acroFields.GetFieldItem("D");
iTextSharp.text.pdf.PdfAction pdfAction = iTextSharp.text.pdf.PdfAction.JavaScript("app.alert('hello');", writer);
iTextSharp.text.pdf.PdfDictionary widgetRefDict = (iTextSharp.text.pdf.PdfDictionary)iTextSharp.text.pdf.PdfReader.GetPdfObject(dateField.GetWidgetRef(0));
iTextSharp.text.pdf.PdfDictionary actionDict = widgetRefDict.GetAsDict(iTextSharp.text.pdf.PdfName.AA);
if (actionDict == null)
{
actionDict = new iTextSharp.text.pdf.PdfDictionary();
// add the newly created action dict
widgetRefDict.Put(iTextSharp.text.pdf.PdfName.AA, actionDict);
}
actionDict.Put(iTextSharp.text.pdf.PdfName.V, pdfAction);
stamper.Close();
reader.Close();
}
byte[] content = outputStream.ToArray();
// Write out PDF from memory stream.
using (FileStream fs = File.Create("d:\\Page1-output.pdf"))
{
fs.Write(content, 0, (int)content.Length);
}
}

Scala/Jasper - How to Merge Multiple PDF in Single Page

I have 60 PDF files I would like to show (Print) in single PDF. I have already tried googling it but it was no use for me, as all PDF append in to a single page. How do I resolve this (I'm an new to this)
Here is my code:
var jasperPrint1 = JasperFillManager.fillReport(jasperReport1, params1, new JREmptyDataSource());
var pages = jasperPrint1.getPages();
for( j <- 0 to pages.size()-1){
var obj = pages.get(j)
jasperPrint.addPage(obj)
}
var outDir: String = java.lang.System.getProperty("user.dir");
separator = java.io.File.separator;
outDir = outDir + separator + "public" + separator + "sample.pdf"
var baos = new java.io.ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
var outputStream = new java.io.FileOutputStream(outDir);
baos.writeTo(outputStream);

Adding page numbers to pdf using iTextSharp on second pass is not working

So as the title says I am trying to add page numbers to an existing pdf document, I have researched this problem and come up with a few tutorials/examples.
Here is the simplest example i can find
My code Compiles and runs successfully however the changes are not reflected in the pdf
my code
byte[] bytes = File.ReadAllBytes(filePath + ".pdf");
PdfReader pdfReader = new PdfReader(bytes);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms,'\0',true))
{
int n = pdfReader.NumberOfPages;
for (int i = 1; i <= n; i++)
{
creatPageCountFooter(i + 1, n).WriteSelectedRows(0, -1, 34, 803, stamper.GetOverContent(i));
//ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
ms.ToArray();
}
pdfReader.Close();
}
File.WriteAllBytes(filePath + ".pdf", bytes);
the function "creatPageCountFooter"
/**
* Create a header table with page X of Y
* #param count the page number
* #param Total the total number of pages
* #return a table that can be used as header
*/
protected PdfPTable creatPageCountFooter(int count,int Total)
{
PdfPTable pageCount = new PdfPTable(3);
pageCount.TotalWidth=250;
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6);
PdfPCell Cell = new PdfPCell(new Phrase(DateTime.Now.ToString("dd MMM yyyy"), times));
Cell.HorizontalAlignment = Element.ALIGN_RIGHT;
Cell.Border = 0;
pageCount.AddCell(Cell);
Cell = new PdfPCell(new Phrase(count.ToString() +" / "+ Total.ToString(), times));
Cell.HorizontalAlignment = Element.ALIGN_MIDDLE;
Cell.Border = 0;
pageCount.AddCell(Cell);
Cell = new PdfPCell(new Phrase("Company name " + DateTime.Now.ToString("yyyy"), times));
Cell.HorizontalAlignment = Element.ALIGN_MIDDLE;
Cell.Border = 0;
pageCount.AddCell(Cell);
return pageCount;
}
As a further note I have checked that this code actually runs and I have tried writing the file over the existing document or creating a new document and both times the changes don't reflect.
I will provide further details if required.
Your code writes the byte[] bytes to a file:
File.WriteAllBytes(filePath + ".pdf", bytes);
But the only code in which that variable is set, is the initial
byte[] bytes = File.ReadAllBytes(filePath + ".pdf");
Thus, it is not surprising that the changes are not reflected in the pdf result file because you simply write the original bytes unchanged.
I assume you meant to set bytes to the contents of the memory stream in this line
ms.ToArray();
but forgot the bytes =. Unfortunately, though, that array retrieval call happens too early, it is still inside the using PdfStamper block:
using (PdfStamper stamper = new PdfStamper(pdfReader, ms,'\0',true))
{
...
ms.ToArray();
}
Just like in the sample you refer to, the array has to be retrieved outside that using block, so that it is retrieved after the PdfStamper implicitly gets closed during disposal. Thus:
using (PdfStamper stamper = new PdfStamper(pdfReader, ms,'\0',true))
{
...
}
bytes = ms.ToArray();

iText for .NET barcode

I try to create a PDF with a EAN13 Bar-code using the iTextSharp library.
I try to generate a barcode with the value "023942432852".
iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);
throws System.IndexOutOfRangeException.
There is the code:
Document pdfdoc = new Document(pageSize, _margSx, _margDx, _margUp, _margBo);
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(_path + #"\Barcode.pdf", FileMode.Create));
pdfdoc.Open();
PdfContentByte cb = writer.DirectContent;
pdfdoc.PageSize.BackgroundColor = BaseColor.GRAY;
BarcodeEAN codeEan = new BarcodeEAN();
if (CreaChecksum)
codeEan.GenerateChecksum = true;
codeEan.ChecksumText = true;
codeEan.CodeType = Barcode.EAN13;
codeEan.Code = barcode;
iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);
imageEAN.ScaleAbsolute(100, 40);
imageEAN.SetAbsolutePosition(pdfdoc.PageSize.Right - 150f, pdfdoc.PageSize.Bottom + 30f);
pdfdoc.Add(imageEAN);
As the name indicates an EAN13 bar code requires 13 digits, just like an EAN8 bar code requires 8 digits. You are trying to create a bar code for this string:
"023942432852"
When I count the number of digits in this string, I only find 12. One digit is missing. Please complete the string so that its length is 13.

Insert merge field in word using open xml

I want to insert a merge field to an existing word doc. Am able to create a xml element of merge field but am not sure on how to append that to the document. Below is my code
Microsoft.Office.Interop.Word.Document wrdDoc = Globals.ThisAddIn.Application.ActiveDocument;
From above I will get the active document
string instructionText = String.Format(" MERGEFIELD {0} \\* MERGEFORMAT", cmbType.Text + "__" + cmbField.Text);
SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };
DocumentFormat.OpenXml.Wordprocessing.Run run1 = new DocumentFormat.OpenXml.Wordprocessing.Run();
RunProperties runProperties1 = new RunProperties();
NoProof noProof1 = new NoProof();
runProperties1.Append(noProof1);
Text text1 = new Text();
text1.Text = String.Format("«{0}»", cmbType.Text + "__" + cmbField.Text);
run1.Append(runProperties1);
run1.Append(text1);
simpleField1.Append(run1);
DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
paragraph.Append(new OpenXmlElement[] { simpleField1 });
Here am creating a paragraph. Now how can i append this paragraph element to the wrdDoc
Word.MailMerge wrdMailMerge;
Word.Selection wrdSelection;
Word.MailMergeFields wrdMergeFields;
Microsoft.Office.Interop.Word.Document wrdDoc = Globals.ThisAddIn.Application.ActiveDocument;
Microsoft.Office.Interop.Word.Application wrdApp = Globals.ThisAddIn.Application;
wrdSelection = wrdApp.Selection;
wrdMailMerge = wrdDoc.MailMerge;
wrdMergeFields = wrdMailMerge.Fields;
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphJustify;
wrdMergeFields.Add(wrdSelection.Range, fieldname);