如何在 C# 中将 PDF 转换为 SVG(教程)

发布: (2025年12月19日 GMT+8 17:46)
3 min read
原文: Dev.to

Source: Dev.to

介绍

本教程说明如何使用托管的 BuildVu Cloud API 在 C# 中将 PDF 文件转换为 SVG,并提供以下示例:

  • IDRsolutions 试用版或云订阅
  • 自托管的 BuildVu 微服务实例

虽然这些服务可以通过标准的 HTTP 请求访问,但本教程使用开源的 C# IDRCloudClient,它为 REST API 提供了易于使用的 C# 包装器。

前置条件

通过 NuGet 安装 idrsolutions-csharp-client 包:

nuget install idrsolutions-csharp-client

代码示例

下面是一个简单的代码示例,演示如何将 PDF 文件转换为 SVG。更多配置选项和高级功能将在后文中说明。

using System;
using System.Collections.Generic;
using idrsolutions_csharp_client;

class ExampleUsage
{
    static void Main(string[] args)
    {
        var client = new IDRCloudClient("https://cloud.idrsolutions.com/cloud/" + IDRCloudClient.BUILDVU);

        try
        {
            Dictionary parameters = new Dictionary
            {
                //["token"] = "Token", // Required only when connecting to the IDRsolutions trial and cloud subscription service
                ["input"] = IDRCloudClient.UPLOAD,
                ["file"] = "path/to/input.pdf"
            };

            Dictionary results = client.Convert(parameters);

            string outputUrl = results.GetValueOrDefault("downloadUrl", "No download URL provided");

            client.DownloadResult(results, "path/to/output/dir");

            Console.WriteLine("Converted: " + outputUrl);
        }
        catch (Exception e)
        {
            Console.WriteLine("Conversion failed: " + e.Message);
        }
    }
}

将返回结果发送到回调 URL

BuildVu 微服务可以接受回调 URL,以在转换完成后报告状态。使用回调 URL 可避免轮询服务。如下所示将回调 URL 传递给 convert 方法。

Dictionary parameters = new Dictionary
{
    //["token"] = "Token", // Required only when connecting to the IDRsolutions trial and cloud subscription service
    ["callbackUrl"] = "http://listener.url",
    ["input"] = IDRCloudClient.UPLOAD,
    ["file"] = "path/to/input.pdf"
};

配置选项

BuildVu API 接受一个字符串化的 JSON 对象,其中包含键值对配置选项,以自定义转换。将这些设置放入参数字典中。用于将 PDF 文件转换为 SVG 的完整配置选项列表请参见此处

["settings"] = "{\"key\":\"value\",\"key\":\"value\"}"

通过 URL 上传

除了上传本地文件外,还可以提供一个 URL,让 BuildVu 微服务下载并转换。将 inputfile 条目替换为以下内容:

["input"] = IDRCloudClient.DOWNLOAD,
["url"] = "http://exampleURL/exampleFile.pdf"

使用身份验证

如果您的自托管 BuildVu 微服务需要用户名和密码,请在创建客户端实例时将其包含进去:

var client = new IDRCloudClient("http://exampleURL.com/" + IDRCloudClient.BUILDVU, "username", "password");
Back to Blog

相关文章

阅读更多 »