-2

我们的要求是使用 ConvertAPI 将存储在数据库中的文件、字节数组转换为 PDF。我们尝试了多种选择,但得到了不同的错误,如下所述。有人可以帮助我们将字节文件格式转换为 PDF 的功能。

错误 1 ​​- 远程服务器返回错误:(400) 错误请求。

  using (var client = new WebClient())
            {
                client.Headers.Add("accept", "application/octet-stream");
                client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                var resultFile = client.UploadData("https://v2.convertapi.com/doc/to/pdf?Secret=**********", byteTemplate);
            }
 

错误 2 - 远程服务器返回错误:(400) 错误请求

      var requestContent = new MultipartFormDataContent();
        ByteArrayContent data = new ByteArrayContent(byteTemplate, 0, byteTemplate.Count());
        requestContent.Add(data, "File", "Files");
        requestContent.Add(new StringContent("**********"), "Secret");
        var authParam = parameters.ContainsKey("secret") ? $"Secret={parameters["secret"]}" : $"Token={parameters["token"]}";
        return new HttpClient().PostAsync($"https://v2.convertapi.com/{srcFormat}/to/{dstFormat}?{authParam}", requestContent).Result;

错误 3 - 代码":5001,"消息":"转换失败。"

或无法访问已处置的对象。对象名称:'System.Net.Http.MultipartFormDataContent'

public static HttpResponseMessage Convert(string srcFormat, string dstFormat, Dictionary<string, string> parameters, byte[] bytetemp, MemoryStream streamTemplate)
    {
        var requestContent = new MultipartFormDataContent();
        streamTemplate.Position = 0;
        requestContent.Add(new StreamContent(streamTemplate), "File", "ABC");
        foreach (var parameter in parameters)
        {
            if (File.Exists(parameter.Value))
            {
            }
            else
            {
                requestContent.Add(new StringContent(parameter.Value), parameter.Key);
            }
        }
        var authParam = parameters.ContainsKey("secret") ? $"Secret={parameters["secret"]}" : $"Token={parameters["token"]}";
        HttpContent rescont = new HttpClient().PostAsync($"https://v2.convertapi.com/{srcFormat}/to/{dstFormat}?{authParam}", requestContent).Result.Content;
        String a = rescont.ReadAsStringAsync().Result;
    }

错误 4 - 远程服务器返回错误:(400) 错误请求。

旧代码与新 URL,使用旧 URL

public static byte[] CovertWordtoPdf(byte[] response)
    {
        byte[] bufferDocxReport;
        bufferDocxReport = response;

        string reportName = "reportname.doc";
        #region Convert DOCX report to PDF format
       WebRequest convertToPdfRequest = WebRequest.Create("https://v2.convertapi.com/docx/to/pdf?Secret=************");
        convertToPdfRequest.Method = "POST";
        var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
        convertToPdfRequest.ContentType = "multipart/form-data; boundary=" + boundary;
        boundary = "--" + boundary;
        using (var requestStream = convertToPdfRequest.GetRequestStream())
        {
            // Write the file
            var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", "name", reportName, Environment.NewLine));
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", "application/octet-stream", Environment.NewLine));
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Write(bufferDocxReport, 0, bufferDocxReport.Length);
            buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
            requestStream.Write(buffer, 0, buffer.Length);
            var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
            requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
        }

        using (var convertToPdfResponse = convertToPdfRequest.GetResponse())
        using (Stream convertToPdfResponseStream = convertToPdfResponse.GetResponseStream())
        {
            bufferDocxReport = ReadToEnd(convertToPdfResponseStream);
        }

        return bufferDocxReport;
        #endregion
    }   

错误 5 - 代码:5001,消息:“转换失败。

var requestContent = new MultipartFormDataContent();
        streamTemplate.Position = 0;
        StreamContent data = new StreamContent(streamTemplate);
        requestContent.Add(data, "File", "Files");
        requestContent.Add(new StringContent("************"), "Secret");
        var authParam = parameters.ContainsKey("secret") ? $"Secret={parameters["secret"]}" : $"Token={parameters["token"]}";
        return new HttpClient().PostAsync($"https://v2.convertapi.com/{srcFormat}/to/{dstFormat}?{authParam}", requestContent).Result;
4

1 回答 1

0

工作解决方案是

const string fileToConvert = @"C:\Projects\_temp\test1.docx";
var bytesToConvert = File.ReadAllBytes(fileToConvert);

var url = new Uri("https://v2.convertapi.com/docx/to/pdf?secret=<YourSecret>");                       
var content = new ByteArrayContent(bytesToConvert);
content.Headers.Add("content-type", "application/octet-stream");
content.Headers.Add("content-disposition", "attachment; filename=\"test1.docx\"");          
var fileBytes = new HttpClient().PostAsync(url, content).Result.Content.ReadAsByteArrayAsync().Result;     

我想指出几个重要的事情:

  • 我们应该将请求的内容类型设置为 application/octet-stream,因为我们在请求正文中发送纯二进制数据。
  • 还应提供 content-disposition 以让 Rest API 端点知道发送了什么数据,在这种情况下是文件。
于 2018-03-28T11:54:40.920 回答