【问题标题】:Replace text with image in PDF using Telerik RadPdfProcessing使用 Telerik RadPdfProcessing 将 PDF 中的文本替换为图像
【发布时间】:2021-02-19 17:09:13
【问题描述】:

我正在使用 Telerik RadPdfProcessing for Xamarin 在移动应用程序中自定义 PDF 文档。 代码必须在文档中搜索“#placeholder#”,并将其替换为用户输入的手写签名。

可以使用以下代码在给定位置插入签名图像:

RadFixedPage last = document.Pages.Last();
FixedContentEditor editor = new FixedContentEditor(last);
editor.Position.Translate(400, 900);
editor.DrawImage(imageSource);

我发现一个forum 说库基本上不支持在页面中查找,因为它一次只允许搜索一个字符:

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);
        //}
    }
}

有人有关于这个主题的最新消息吗?

【问题讨论】:

    标签: pdf xamarin.forms telerik telerik-pdfprocessing


    【解决方案1】:

    您可以通过以下方式实现:

    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));
    

    另一种选择是通过搜索其名称来替换预定义的Field。这样您就可以在文档页面上预先分配空间。

    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);
    

    【讨论】:

    • 马丁,谢谢您的建议。出于某种原因,内容元素上的 foreach 循环没有返回我所期望的,但它可能是特定文档的问题。我在其他项目上测试过它,它有效!也感谢您提供第二个选项,不幸的是它不适用于我的情况,因为我没有字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多