private void highlightPDFAnnotation(string outputFile, int pageno, string[] splitText)
{
try
{
PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(outputFile));
using (FileStream fs = new FileStream(outputFile, FileMode.Open, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader, fs))
{
myLocationTextExtractionStrategy strategy = new myLocationTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(reader, pageno, strategy);
for (int i = 0; i < splitText.Length; i++)
{
List<iTextSharp.text.Rectangle> MatchesFound = strategy.GetTextLocations(splitText[i].Trim(), StringComparison.CurrentCultureIgnoreCase);
foreach (Rectangle rect in MatchesFound)
{
float[] quad = { rect.Left - 3.0f, rect.Bottom, rect.Right, rect.Bottom, rect.Left - 3.0f, rect.Top + 1.0f, rect.Right, rect.Top + 1.0f };
//Create our hightlight
PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, null, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
//Set the color
highlight.Color = BaseColor.YELLOW;
PdfAppearance appearance = PdfAppearance.CreateAppearance(stamper.Writer, rect.Width, rect.Height);
PdfGState state = new PdfGState();
state.BlendMode = new PdfName("Multiply");
appearance.SetGState(state);
appearance.Rectangle(0, 0, rect.Width, rect.Height);
appearance.SetColorFill(BaseColor.YELLOW);
appearance.Fill();
highlight.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance);
//Add the annotation
stamper.AddAnnotation(highlight, pageno);
highlight.Clear();
}
}
stamper.Close();
stamper.Dispose();
}
fs.Close();
fs.Dispose();
}
reader.Close();
reader = null;
}
catch (Exception ex)
{
throw;
}
}
第四次尝试后,它会抛出&#34;对象引用未设置为对象的实例。&#34; 错误。
Stacktrace:
at iTextSharp.text.pdf.PdfReader.PageRefs.ReadPages()
在iTextSharp.text.pdf.PdfReader.PageRefs..ctor(PdfReader阅读器)
在iTextSharp.text.pdf.PdfReader.ReadPages()
在iTextSharp.text.pdf.PdfReader.ReadPdf()
在iTextSharp.text.pdf.PdfReader..ctor(Byte [] pdfIn,Byte [] ownerPassword)在iTextSharp.text.pdf.PdfReader..ctor(Byte [] pdfIn) at bottom.highlightPDFAnnotation(String outputFile,Int32 pageno, String [] splitText)