I'm using Telerik RadPdfProcessing for Xamarin to customize a PDF document in a mobile application. The code must search for a "#placeholder#" inside the document and replace it with the signature hand typed by the user.
The signature image can be inserted at a given position with this code:
RadFixedPage last = document.Pages.Last();
FixedContentEditor editor = new FixedContentEditor(last);
editor.Position.Translate(400, 900);
editor.DrawImage(imageSource);
And I've found a forum saying that find in page is basically not supported by the library, since it allows only to search one character at a time:
foreach (var contentElement in last.Content) {
if (contentElement is TextFragment) {
TextFragment fragment = (TextFragment) contentElement;
string text = fragment.Text;
//** THIS DOESN'T WORK! **
//if ("#placeholder#" == text) {
// fragment.Text = "";
// editor.Position = fragment.Position;
// editor.DrawImage(imageSource);
//}
}
}
Does anyone have more recent news on this subject?
You can achieve this in the following way:
RadFixedPage lastPage = document.Pages.Last();
IPosition position = new SimplePosition();
foreach (ContentElementBase contentElement in lastPage.Content.ToList())
{
if (contentElement is TextFragment fragment)
{
if (fragment.Text == "#placeholder#")
{
position = fragment.Position;
lastPage.Content.Remove(fragment);
}
}
}
ImageSource imageSource;
using (FileStream source = File.Open("image1.jpg", FileMode.Open))
{
imageSource = new ImageSource(source);
}
FixedContentEditor editor = new FixedContentEditor(lastPage);
editor.Position = position;
editor.DrawImage(imageSource, new Size(50, 50));
Another option could be to replace a predefined Field by searching for its name. This way you can pre-allocate space on the document's page.
RadFixedPage firstPage = document.Pages[0];
Annotation field = firstPage.Annotations.First(a => ((VariableContentWidget)a).Field.Name == "SampleField");
System.Windows.Rect fieldRect = field.Rect;
string imagePath = "image1.jpg";
ImageSource imageSource;
using (FileStream source = File.Open(imagePath, FileMode.Open))
{
imageSource = new ImageSource(source);
}
IPosition position = new SimplePosition();
simplePosition.Translate(fieldRect.X, fieldRect.Y);
Image image = new Image
{
ImageSource = imageSource,
Position = position,
Width = fieldRect.Width,
Height = fieldRect.Height
};
firstPage.Annotations.Remove(field);
firstPage.Content.Add(image);