iTextSharp: Trying to make TextField transparent: PdfContentByte is nothing - itext

I want to add textfields to my PDF.
These textfields' backgrounds should be transparent.
I have found an example on the web that showed how to do this the following way:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TransparencyPDF.pdf"));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfGState gs1 = new PdfGState();
gs1.setFillOpacity(0.5f);
cb.setGState(gs1);
However, in my code, I don't have a PDFWriter. I have a PDFStamper.
But its properties look perfectly the same, so I adopt it like this:
Dim cb As PdfContentByte = stamper.GetOverContent(0)
Dim gs As New PdfGState
gs.FillOpacity = 0.5
cb.SetGState(gs)
The last line throws the error "System.NullReferenceException: cb is nothing."
What am I doing wrong here?
Thank you.
This is my entire code:
Dim stamper As PdfStamper = New PdfStamper(New PdfReader(sInputFile), File.Create(sOutputFile))
Dim iPageNumer As Integer = 1
Dim tf As TextField
tf = New TextField(stamper.Writer, New iTextSharp.text.Rectangle(iLowerLeftX, iLowerLeftY, iUpperRightX, iUpperRightY), n.Name)
Dim bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, False)
With tf
.Alignment = Element.ALIGN_LEFT And Element.ALIGN_MIDDLE ' Element.ALIGN_CENTER And Element.ALIGN_MIDDLE
.BackgroundColor = GrayColor.WHITE
.BorderColor = Color.RED
.BorderStyle = PdfBorderDictionary.STYLE_SOLID
.DefaultText = "This is a new text field."
.Font = bf
.FontSize = 7
.MaxCharacterLength = 25
.Options = TextField.BORDER_WIDTH_MEDIUM ' TextField.REQUIRED Or TextField.MULTILINE
.Rotation = 0 '90
.Text = "" 'This is the assigned value."
End With
stamper.AddAnnotation(tf.GetTextField(), iPageNumer)
Dim cb As PdfContentByte = stamper.GetOverContent(0)
Dim gs As New PdfGState
gs.FillOpacity = 0.5
cb.SetGState(gs) 'This line throws the error. cb is nothing. Why?
stamper.Close()

The problem with
Dim cb As PdfContentByte = stamper.GetOverContent(0)
is that it requests the OverContent of page 0 while page numbering in iText starts at 1. Thus, use
Dim cb As PdfContentByte = stamper.GetOverContent(1)
instead.

Related

iText Text Expansion Not Working in Certain Conditions

The following code will generate a pdf that will not use the specified text expansions when read out loud. It seems that adding the image in a container is causing the problem.
void Main()
{
using(var ms = new MemoryStream())
{
var doc = new Document(PageSize.LETTER, 72, 72, 72, 72);
var writer = PdfWriter.GetInstance(doc, ms);
writer.SetTagged();
doc.Open();
var c1 = new Chunk("ABC");
c1.SetTextExpansion("the alphabet");
var p1 = new Paragraph();
p1.Add(c1);
doc.Add(p1);
// Adding this image to the document as img > chunk > doc causes the text expansion not to work.
// Adding this image to the document as img > doc works
var t = writer.DirectContent.CreateTemplate(6, 6);
t.SetLineWidth(1f);
t.Circle(3f, 3f, 1.5f);
t.SetGrayFill(0);
t.FillStroke();
var i = iTextSharp.text.Image.GetInstance(t);
var c2 = new Chunk(i, 0, 0);
doc.Add(c2);
var c3 = new Chunk("foobar");
c3.SetTextExpansion("foo bar");
var p3 = new Paragraph();
p3.Add(c3);
doc.Add(p3);
doc.Close();
ms.Flush();
File.WriteAllBytes("d:\\expansion.pdf", ms.ToArray());
}
}
Is this just me doing something wrong or a bug?
While this doesn't read out loud correctly in Adobe Reader, it does in JAWS. So it sounds like this is a reader issue and not necessarily an iText issue.

iText basefont mingliu.ttc italic cannot work

I want to show text in mingliu font style italic, using the following code but fail, the output is still standard style, not italic (I am using iText 2).
PdfContentByte cb = writer.getDirectContent();
..................
String ttfPath = null;
ttfPath = BaseSection.class.getResource("/WEB-INF/lib/mingliu.ttc").getPath();
try{
this.bfi = BaseFont.createFont(ttfPath+",0,Italic", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
cb.setFontAndSize(bfi, 8);
..........
cb.showText(companyText);
}
Any method to show the mingliu text in italic style using BaseFont.createFont?
Thanks.
I find the following can solve my problem
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
String ttfPath = BaseSection.class.getResource("/WEB-INF/lib/mingliu.ttc").getPath();
bf = BaseFont.createFont(ttfPath+",0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
String companyText = "abc";
Font font = new Font(bf, 8, Font.ITALIC);
Chunk chunk = new Chunk(companyTextC, font);
Phrase phrase = new Phrase(chunk);
ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, phrase, document.right(), 1, 0);
cb.restoreState();
Hope this can help others with similar problem.

iTextSharp does not render header/footer when using element generated by XmlWorkerHelper

I am trying to add header/footer to a PDF whose content is otherwise generated by XMLWorkerHelper. Not sure if it's a placement issue but I can't see the header/footer.
This is in an ASP.NET MVC app using iTextSharp and XmlWorker packages ver 5.4.4 from Nuget.
Code to generate PDF is as follows:
private byte[] ParseXmlToPdf(string html)
{
XhtmlToListHelper xhtmlHelper = new XhtmlToListHelper();
Document document = new Document(PageSize.A4, 30, 30, 90, 90);
MemoryStream msOutput = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
writer.PageEvent = new TextSharpPageEventHelper();
document.Open();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/themes/mytheme.css"), true);
var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
var worker = new XMLWorker(pipeline, true);
var parser = new XMLParser();
parser.AddListener(worker);
using (TextReader sr = new StringReader(html))
{
parser.Parse(sr);
}
//string text = "Some Random Text";
//for (int k = 0; k < 8; ++k)
//{
// text += " " + text;
// Paragraph p = new Paragraph(text);
// p.SpacingBefore = 8f;
// document.Add(p);
//}
worker.Close();
document.Close();
return msOutput.ToArray();
}
Now instead of using these three lines
using (TextReader sr = new StringReader(html))
{
parser.Parse(sr);
}
if I comment them out and uncomment the code to add a random Paragraph of text (commented in above sample), I see the header/footer along with the random text.
What am I doing wrong?
The EventHandler is as follows:
public class TextSharpPageEventHelper : PdfPageEventHelper
{
public Image ImageHeader { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
float cellHeight = document.TopMargin;
Rectangle page = document.PageSize;
PdfPTable head = new PdfPTable(2);
head.TotalWidth = page.Width;
PdfPCell c = new PdfPCell(ImageHeader, true);
c.HorizontalAlignment = Element.ALIGN_RIGHT;
c.FixedHeight = cellHeight;
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase(
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT",
new Font(Font.FontFamily.COURIER, 8)
));
c.Border = PdfPCell.TOP_BORDER | PdfPCell.RIGHT_BORDER | PdfPCell.BOTTOM_BORDER | PdfPCell.LEFT_BORDER;
c.VerticalAlignment = Element.ALIGN_BOTTOM;
c.FixedHeight = cellHeight;
head.AddCell(c);
head.WriteSelectedRows(
0, -1, // first/last row; -1 flags all write all rows
0, // left offset
// ** bottom** yPos of the table
page.Height - cellHeight + head.TotalHeight,
writer.DirectContent
);
}
}
Feeling angry and stupid for having lost more than two hours of my life to Windows 8.1! Apparently the built in PDF Reader app isn't competent enough to show 'Headers'/'Footers'. Installed Foxit Reader and opened the output and it shows the Headers allright!
I guess I should try with Adobe Reader too!!!
UPDATES:
I tried opening the generated PDF in Adobe Acrobat reader and finally saw some errors. This made me look at the HTML that I was sending to the XMLWorkerHelper more closely. The structure of the HTML had <div>s inside <table>s and that was tripping up the generated PDF. I cleaned up the HTML to ensure <table> inside <table> and thereafter the PDF came out clean in all readers.
Long story short, the code above is fine, but if you are testing for PDF's correctness, have Adobe Acrobat Reader handy at a minimum. Other readers behave unpredictably as in either not reporting errors or incorrectly rendering the PDF.

Using iTextSharp v4.1.2, how do I add an image to the header?

I can add a text header in iTextSharp v4.1.2 but how do I add an image instead of text? I am currently using a text header but I would like to replace it with an image.
' Create a Document object
Dim doc As Document = New Document(PageSize.LETTER)
doc.SetMargins(pageMarginLeft, pageMarginRight, pageMarginTopBottom, pageMarginTopBottom)
' Create a new PdfWriter object, specifying the output stream
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream)
' Set header and footer
Dim headerFont As iTextSharp.text.Font = FontFactory.GetFont("Arial", 12, iTextSharp.text.Color.BLUE)
Dim header As New HeaderFooter(New Paragraph("VOLUNTEER MASTER SCHEDULE", headerFont), False)
Dim footerFont As iTextSharp.text.Font = FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)
Dim footer As New HeaderFooter(New Phrase("Page: ", footerFont), True)
doc.Header = header
doc.Footer = footer
' Open the Document for writing
doc.Open()

ITextSharp, Assigning a font to List within a cell?

Is there a way to assign a font to a list that is added to table cell in ITextsharp. I'm sure it must be straightforward but I'm missing it.
Dim tblSignature As New PdfPTable(1)
tblSignature.WidthPercentage = 90.0F
Dim _baseFont As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED)
Dim _bFont As New Font(_baseFont, 4, Font.ITALIC, Color.RED)
Dim cell As New PdfPCell(New Phrase(TheItem.Value, _bFont))
TheParagraph.Font = _bFont
Dim list As New List(list.UNORDERED, 25.0F)
list.SetListSymbol("[ ]")
If ListItems.Count > 0 Then
For Each ListItem In .ListItems
//I have tried adding as chunk/phrase and applying font but no joy
//Item not added to cell
//list.Add(New Chunk(ListItem, _bFont))
list.Add(ListItem)
Next
list.IndentationLeft = 5.0F
cell.AddElement(list)
End If
cell.Colspan = 6
cell.HorizontalAlignment = 0
cell.PaddingBottom = 5.0F
cell.PaddingLeft = 5.0F
cell.PaddingRight = 5.0F
'' add to doc
tblSignature.AddCell(cell)
TheParagraph.Add(tblSignature)
Does anyone know How I'd change this so that the list/cell has the specific font I've set at the top.
Cheers
The iTextSharp.text.ListItem object has an iTextSharp.text.Font property you can set.
Please note that declarations such as new PdfPCell or new Phrase will not work with iTextSharp.text.List's add method.But both of them fairly work with PdfPTable.
I used iTextSharp.text.List for one of my software's pdf print out in the following ways.I hope this may be useful to you also.
This is a program which is used in one of my software developed with vb.net(visual studio 2010 and windows 7 platform) and iTextSharp latest version.
for pdf print out.It demonstrates how we can manupulate iTextSharp.text.List's font properties.
Dim doc1 As New Document()
Dim pathpdf As String = "C:/temp"
'path = ServerMapPath("PDFs");
PdfWriter.GetInstance(doc1, New FileStream(pathpdf + "/Doc1.pdf", FileMode.Create))
' Now to begin actually working with the document, open it, , add a new list,and, then close it:
doc1.Open()
Dim fnt1 As Font = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL)
Dim fnt2 As Font = FontFactory.GetFont(FontFactory.HELVETICA, 14, iTextSharp.text.Font.BOLD)
Dim fnt3 As Font = FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL)
Dim lst3 As New iTextSharp.text.List()
lst3.SetListSymbol("")
'add a list item in bold letters.
Dim m_DataHeadOnly As String
m_DataHeadOnly = "This is the itextsharp font setting with list"
lst3.Add(New iTextSharp.text.ListItem(m_DataHeadOnly, fnt2))
doc1.add(lst3)
doc1.close()