I noticed if we clear all fields on a Document prior to stamping text, we end up with a document missing font information, and is invalid.
public void ClearFormFields(string savePath, List<string> fields = null, bool saveAfterUpdate = false)
{
_logger.LogTrace("{method} | Entering. savePath: {savePath}", nameof(ClearFormFields), savePath);
if (fields == null)
{
fields = _document.Form.Fields.Select(f => f.FullName).ToList();
}
foreach (var f in fields)
{
_pdfForm.FillField(f, (string)null);
}
if (saveAfterUpdate)
{
Save(savePath);
}
}
private static Document StampTextIntoDocument(List<SearchTextPlacementModel> searchPlacements, Document doc)
{
foreach (var placement in searchPlacements)
{
var p = placement;
if (!string.IsNullOrEmpty(p.FormField))
{
p = GetFormFieldCoordinates(doc, p.FormField, p.Instance, placement);
}
else if (!string.IsNullOrEmpty(p.SearchText))
{
p = GetTextCoordinates(doc, placement);
}
p.Left += p.XOffset;
p.Bottom += p.YOffset;
if (p.PageNumber > 0 && p.Value != null)
{
// Get particular page
var pdfPage = doc.Pages[p.PageNumber];
// Create text fragment
var textFragment = new TextFragment(p.Value) { Position = new Position(p.Left, p.Bottom) };
// Set text properties
textFragment.TextState.FontSize = p.FontSize;
try
{
textFragment.TextState.Font = FontRepository.FindFont(p.FontName);
}
catch (Exception)
{
textFragment.TextState.Font = FontRepository.FindFont("Helvetica");
}
textFragment.TextState.Font.IsEmbedded = true;
switch (p.FontColor)
{
case FontColorTypes.Blue:
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(Color.Blue);
break;
case FontColorTypes.Red:
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(Color.Red);
break;
default:
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(Color.Black);
break;
}
// Create TextBuilder object
var textBuilder = new TextBuilder(pdfPage);
// Append the text fragment to the PDF page
textBuilder.AppendText(textFragment);
}
}
return doc;
}