正在尝试使用txt转换convertapi.com公司Python 3.2.2

2024-05-18 15:47:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python和编程还不熟悉。我正在尝试将一个.txt文件转换为pdf,我搜索了一下,但找不到一个库来完成这项工作,这是在python3.2.2中现成的,所以我使用的是一个web服务。在

这是我的代码:我得到的“文件”参数不能为空

import urllib.request, urllib.parse, http.client, os
#import requests

#ejemplo txt
txt = open("test.txt", 'rb')

def txtPdf(txt):
    url = "http://do.convertapi.com/text2Pdf"
    archivo =  open("temp.pdf", "wb")
    valores = {"File": txt}

    datos = urllib.parse.urlencode(valores).encode("utf-8")
    solicitar = urllib.request.urlopen(url, data = datos)
    archivo.write(solicitar.read())
    archivo.close()

txtPdf(txt)

谢谢你的帮助!在


Tags: 文件importtxthttpurlpdfparserequest
2条回答
$url = 'https://do.convertapi.com/Text2Pdf';
$fp = fopen("convertedfile.pdf", "w");
$postdata =  array('ApiKey' => $apiKey, 'file'=>"@/example.txt");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_FILE, $fp);
$result=curl_exec ($ch);
$headers = curl_getinfo($ch);
curl_close($ch);

很容易,如果您可以使用请求:

import requests

txtPdf(filename):
    url = "http://do.convertapi.com/text2Pdf"
    archivo =  open("temp.pdf", "wb")

    response = requests.post(url,
        files={'filename': open(filename,'rb')}
    )

    archivo.write(response.content)
    archivo.close()

txtPdf('test.txt')

相关问题 更多 >

    热门问题