首页 文章

使用ConvertAPI将字节转换为PDF

提问于
浏览
-2

我们的要求是使用ConvertAPI将存储在数据库中的文件,字节数组转换为PDF . 我们尝试了多种选择,但是如下所述,我们会遇到不同的错有人可以帮助我们将Byte文件格式转换为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;

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 endpoints 知道发送了什么数据,在这种情况下它是文件 .

相关问题