使用ComPDFKit以编程方式编辑PDF文件

ComPDFKit · 2022-11-23 11:32:36 · 445661 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2022-11-23 11:32:36 的主题,其中的信息可能已经有所发展或是发生改变。

导入 PDF 文件


一旦完成集成 ComPDFKit PDF SDK,就可以通过 CPDFDocument 对象打开和显示 PDF 文档。

// Get the path of a PDF
string filePath ="";
var dlg = new OpenFileDialog();
dlg.Filter = "PDF Files (*.pdf)|*.pdf";
if (dlg.ShowDialog() == true)
{
filePath = dlg.FileName;
}
else
{
return;
}
// Initialize a CPDFDocument object with the path to the PDF file

CPDFDocument document = CPDFDocument.InitWithFilePath(filePath);
if(document==null)
{
return;
}
if(document.ErrorType != CPDFDocumentError.CPDFDocumentErrorSuccess
&& document.ErrorType != CPDFDocumentError.CPDFDocumentPasswordError)
{
return;
}


编辑PDF


ComPDFKit包含了成熟完整的PDF功能,包括查看、编辑、注释、填表、转换、安全、编辑、OCR、导航等。在下一节中,我们将介绍如何实现这些功能。如果您对其他功能感兴趣,请阅读相关文档或博客。


1. 插入 PDF 页面:

假设您要添加另一个 PDF 文件中的第一个 PDF 页面。并且您想在第一个 PDF 页面之前添加页面。按照此处的代码示例并尝试执行此操作。

CPDFDocument otherDocument = CPDFDocument.InitWithFilePath("***");
document.ImportPagesAtIndex(otherDocument, "0", 0);
otherDocument.Release();


2. Annotation:添加文字说明

插入 PDF 页面后,还需要进行其他处理。例如,当一行字可能需要更多细节来解释时,您可以使用文本注释。在这里,您可以找到有关如何添加文本注释的方法。


3. 注释:突出 PDF 的内容

现在,您需要突出一些关键字。ComPDFKit 支持执行此操作的常规方法,例如突出显示、下划线、墨水等。以下代码显示了在第 5 页高亮显示所有关键字“Step”的方法。

CPDFPage page = document.PageAtIndex(4);
if (page == null)
    return;

List rects = new List();
CPDFTextPage textPage = page.GetTextPage();
CPDFTextSearcher searcher = new CPDFTextSearcher();
int findIndex = 0;

if (searcher.FindStart(textPage, "Step", C_Search_Options.Search_Case_Sensitive, findIndex))
{
    CRect textRect = new CRect();
    string textContent = "";
    while (searcher.FindNext(page, textPage, ref textRect, ref textContent, ref findIndex))
    {
        rects.Add(textRect);
    }
}
searcher.FindClose();

CPDFHighlightAnnotation highlight = page.CreateAnnot(C_ANNOTATION_TYPE.C_ANNOTATION_HIGHLIGHT) as CPDFHighlightAnnotation;
byte[] color = { 0, 255, 0 };
highlight.SetColor(color);
highlight.SetTransparency(120);
highlight.SetQuardRects(rects);
highlight.UpdateAp();


4. 保存所做的更改

完成所有更改后,我们可以保存它并完成我们的使用。这是将您所做的所有更改保存在新 PDF 文件中的代码方法。

document.WriteToFilePath("newFilePath");
document.Release();

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

445661 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传