简体   繁体   English

将编码字符串转换为字节,然后写入 PDF 文件不起作用 - 这是哪种编码?

[英]Transforming encoding string to bytes and then writing PDF file not working - What kind of encoding is this?

EDIT: This is solved.编辑:这已经解决了。 Thank you Jeremy Lakeman for your comment, it put me on the right track.感谢 Jeremy Lakeman 的评论,它让我走上了正轨。

I have a PDF file content string that I am trying to use to produce a PDF file.我有一个 PDF 文件内容字符串,我试图用它来生成 PDF 文件。

EDIT: The encoded string looks like this: image or google doc: https://docs.google.com/document/d/1I4UtmAIDYRTvCjd7005jnfP0GTOAauiF0hRGB3K6w1s/edit?usp=sharing编辑:编码的字符串如下所示:图像或谷歌文档: https://docs.google.com/document/d/1I4UtmAIDYRTvCjd7005jnfP0GTOAauiF0hRGB3K6w1s/edit?usp=sharing

Part of the problem is certainly that I have not dealt with any encoding so far in my experience, so please forgive me for that.部分问题当然是我到目前为止还没有处理过任何编码,所以请原谅我。

I'm trying to handle the conversion and writing of the file like this:我正在尝试像这样处理文件的转换和写入:

var bytes = System.Text.Encoding.Unicode.GetBytes(FileContentString);
File.WriteAllBytes(filePath, bytes);

This does produce a PDF file, but when I try to open it, Edge PDF Viewer says, "We can't open this file."这确实会生成一个 PDF 文件,但是当我尝试打开它时,Edge PDF 查看器会说:“我们无法打开这个文件。”

In addition to Unicode, I've tried handling the string as UTF-8 and UTF-32 with varied results.除了 Unicode 之外,我还尝试将字符串处理为 UTF-8 和 UTF-32,结果各不相同。 All of these options do write the file, but the file either does not open or displays a blank page instead.所有这些选项都会写入文件,但文件要么不打开,要么显示空白页。

Do you know what kind of encoding this is?你知道这是什么编码吗? I sure don't.我当然不会。 Or, am I just handling this wrong in general?或者,我只是在处理这个错误吗?

Pro tip: never read a file's contents as a string and then try to convert it back to raw bytes if you can avoid it.专业提示:永远不要将文件的内容作为字符串读取,然后在可以避免的情况下尝试将其转换回原始字节。 In this case, my contents were being read like so:在这种情况下,我的内容是这样读取的:

HttpResponseMessage response = await _httpClient.SendAsync(request);
var content = response.Content.ReadAsStringAsync();

Simply switching it to:只需将其切换为:

var content = response.Content.ReadAsByteArrayAsync();

And then:接着:

File.WriteAllBytes(filePath, content);

Did the trick.成功了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM