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.
Related
As the picture show , I need to get byte array from ByteRange to do some verify , they are 0 to 840 and 960 to 1200.
I found the similar question : In Itext 7, how to get the range stream to sign a pdf?
iText in its own verification code needs to do the same thing. It does so in its SignatureUtil class. Thus, one can simply borrow from that code, e.g. like this:
try ( PdfReader pdfReader = new PdfReader(SOURCE_PDF);
PdfDocument pdfDocument = new PdfDocument(pdfReader);) {
SignatureUtil signatureUtil = new SignatureUtil(pdfDocument);
for (String name : signatureUtil.getSignatureNames()) {
PdfSignature signature = signatureUtil.getSignature(name);
PdfArray b = signature.getByteRange();
RandomAccessFileOrArray rf = pdfReader.getSafeFile();
try ( InputStream rg = new RASInputStream(new RandomAccessSourceFactory().createRanged(rf.createSourceView(), SignatureUtil.asLongArray(b)));
OutputStream result = TARGET_STREAM_FOR_name_BYTES) {
byte[] buf = new byte[8192];
int rd;
while ((rd = rg.read(buf, 0, buf.length)) > 0) {
result.write(buf, 0, rd);
}
}
}
}
(RetrieveSignedRanges test testExtractSignedBytes)
If you want the byte range as a byte[] in memory, you can use a ByteArrayOutputStream as TARGET_STREAM_FOR_name_BYTES and retrieve the resulting byte array from it.
The following code works nicely with iText 5:
LEVEL = PdfAConformanceLevel.PDF_A_3A
writer = PdfAWriter.getInstance(document, baos, LEVEL)
What is the correct syntax for iText 7?
Where can I find examples and documentation about iText 7?
why so negative? Seems like you want to put extra pressure on me to write documentation. That's kind of frustrating. I think that encouragement works better. Nevertheless, your claim that there's no documentation is wrong.
See Chapter 7: Creating PDF/UA and PDF/A documents of the iText 7: Jump-Start Tutorial
You overlooked the UnitedStates_PDFA_3a example in which we have a CSV file that we convert to a PDF/A-3 document adding that CSV file as attachment.
public void createPdf(String dest) throws IOException, XMPException {
PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
PdfAConformanceLevel.PDF_A_3A,
new PdfOutputIntent("Custom", "", "http://www.color.org",
"sRGB IEC61966-2.1", new FileInputStream(INTENT)));
Document document = new Document(pdf, PageSize.A4.rotate());
document.setMargins(20, 20, 20, 20);
//Setting some required parameters
pdf.setTagged();
pdf.getCatalog().setLang(new PdfString("en-US"));
pdf.getCatalog().setViewerPreferences(
new PdfViewerPreferences().setDisplayDocTitle(true));
PdfDocumentInfo info = pdf.getDocumentInfo();
info.setTitle("iText7 PDF/A-3 example");
//Add attachment
PdfDictionary parameters = new PdfDictionary();
parameters.put(PdfName.ModDate, new PdfDate().getPdfObject());
PdfFileSpec fileSpec = PdfFileSpec.createEmbeddedFileSpec(
pdf, Files.readAllBytes(Paths.get(DATA)), "united_states.csv",
"united_states.csv", new PdfName("text/csv"), parameters,
PdfName.Data, false);
fileSpec.put(new PdfName("AFRelationship"), new PdfName("Data"));
pdf.addFileAttachment("united_states.csv", fileSpec);
PdfArray array = new PdfArray();
array.add(fileSpec.getPdfObject().getIndirectReference());
pdf.getCatalog().put(new PdfName("AF"), array);
//Embed fonts
PdfFont font = PdfFontFactory.createFont(FONT, true);
PdfFont bold = PdfFontFactory.createFont(BOLD_FONT, true);
// Create content
Table table = new Table(new float[]{4, 1, 3, 4, 3, 3, 3, 3, 1});
table.setWidthPercent(100);
BufferedReader br = new BufferedReader(new FileReader(DATA));
String line = br.readLine();
process(table, line, bold, true);
while ((line = br.readLine()) != null) {
process(table, line, font, false);
}
br.close();
document.add(table);
//Close document
document.close();
}
public void process(Table table, String line, PdfFont font, boolean isHeader) {
StringTokenizer tokenizer = new StringTokenizer(line, ";");
while (tokenizer.hasMoreTokens()) {
if (isHeader) {
table.addHeaderCell(new Cell().setHorizontalAlignment(HorizontalAlignment.CENTER).add(new Paragraph(tokenizer.nextToken()).setHorizontalAlignment(HorizontalAlignment.CENTER).setFont(font)));
} else {
table.addCell(new Cell().setHorizontalAlignment(HorizontalAlignment.CENTER).add(new Paragraph(tokenizer.nextToken()).setHorizontalAlignment(HorizontalAlignment.CENTER).setFont(font)));
}
}
}
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();
Using itextsharp, I'm attempting to set the font size of my form's text fields to auto.
I'm currently doing something like this:
Object d = 0.0;
PdfReader reader = new PdfReader(path);
byte [] pdf;
using (var ms = new MemoryStream())
{
PdfStamper stamper = new PdfStamper(reader, ms);
AcroFields fields = stamper.AcroFields;
foreach (var f in fields.Fields.Keys)
{
fields.SetFieldProperty(f, "textsize", d, null);
}
}
But I'm getting the following error:
System.InvalidCastException: Specified cast is not valid.
at iTextSharp.text.pdf.AcroFields.SetFieldProperty(String field, String name, Object value, Int32[] inst)
How can I fix this?
Using 0f instead of d in the call SetFieldProperty let me change the font size to auto.
When I am trying to generate PDF from HTML, some Turkish characters like ĞÜŞİÖÇ ğüşıöç are missing in PDF, I see a space in place of these characters but i want to print that character.
My code is:
public virtual void print pdf(string html, int id)
{
String htmlText = html.ToString();
Document document = new Document();
string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+id+".pdf",
FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw =
new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(htmlText));
document.Close();
}
please reply i need suggestion
...
regards
I have finally find a solution for this problem, by this you can print all Turkish characters.
String htmlText = html.ToString();
Document document = new Document();
string filePath = HostingEnvironment.MapPath("~/Content/Pdf/");
PdfWriter.GetInstance(document, new FileStream(filePath + "\\pdf-"+Name+".pdf", FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
FontFactory.Register(Path.Combine(_webHelper.MapPath("~/App_Data/Pdf/arial.ttf")), "Garamond"); // just give a path of arial.ttf
StyleSheet css = new StyleSheet();
css.LoadTagStyle("body", "face", "Garamond");
css.LoadTagStyle("body", "encoding", "Identity-H");
css.LoadTagStyle("body", "size", "12pt");
hw.SetStyleSheet(css);
hw.Parse(new StringReader(htmlText));