使用 python 或 .net core 将文本文件嵌入到 RTF 文件中
Embedding text file into RTF file with python or .net core
我有一个要求,其中包括将文件嵌入(文本文件)到动态生成的 RTF 文件中。
我目前能够毫无问题地生成 RTF,但我还需要将一个或多个 txt 文件嵌入其中。
我做了一些研究,也研究了 rtf 规范。看起来可能有一种方法可以用 \object 标签来做到这一点,但据我了解 \objdata 内容应该是 OLE 格式。这是唯一的方法吗? (我希望我可以包含字节数组格式)或者有什么方法可以将 txt 文件内容转换成这种格式以便我可以包含?
我目前有几个用 python 和 c#(dotnet 核心)编写的微服务,它们都是 运行 在 linux 环境上的 docker 容器上。所以最好我需要一种适合这些的方法。
提前致谢。
Aspose.Words 允许将嵌入的 OLE 对象插入到 Word 文档中,它具有 .NET Standard 2.0 版本。
https://apireference.aspose.com/net/words/aspose.words.documentbuilder/insertoleobject/methods/2
我在这里使用了一个实用的解决方案,当文本文件应该嵌入到 RTF 文档中时,它会起作用。
- 将所需文档另存为 RTF,并在要替换的文本位置添加虚拟文本。
- 使用文本编辑器打开此 RTF,并将
\par
行替换为替换标记 [!!! replace me !!!]
。
发件人:
... prefix rtf stuff ...
\par text foo
\par bar text
\par text baz
... suffix rtf stuff ...
收件人:
... prefix rtf stuff ...
[!!! replace me !!!]
... suffix rtf stuff ...
- 另存为template.rtf
- 在 C# 中,读取要嵌入到字符串中的文本文件,每行前面加上
\par<space>
。将模板读入第二个字符串,然后用第一个字符串替换标记。
- 另存为new.rtf。
这是一个示例(抱歉,仅适用于 Perl,C# 也应该是 10 行):
#!/usr/bin/perl
use strict;
my $contents = "";
my $first = 1;
while(<>) {
if (!$first) {
$contents .= "\par ".$_;
} else {
$contents .= $_;
$first = 0;
}
}
my $file = 'template.rtf';
open my $fh, '<', $file or die;
$/ = undef;
my $data = <$fh>;
close $fh;
$data =~ s/\[!!! replace me !!!\]/$contents/g;
print $data;
这样称呼它:
perl mkrtf.pl <test.lst >test.rtf
我有一个要求,其中包括将文件嵌入(文本文件)到动态生成的 RTF 文件中。
我目前能够毫无问题地生成 RTF,但我还需要将一个或多个 txt 文件嵌入其中。
我做了一些研究,也研究了 rtf 规范。看起来可能有一种方法可以用 \object 标签来做到这一点,但据我了解 \objdata 内容应该是 OLE 格式。这是唯一的方法吗? (我希望我可以包含字节数组格式)或者有什么方法可以将 txt 文件内容转换成这种格式以便我可以包含?
我目前有几个用 python 和 c#(dotnet 核心)编写的微服务,它们都是 运行 在 linux 环境上的 docker 容器上。所以最好我需要一种适合这些的方法。
提前致谢。
Aspose.Words 允许将嵌入的 OLE 对象插入到 Word 文档中,它具有 .NET Standard 2.0 版本。 https://apireference.aspose.com/net/words/aspose.words.documentbuilder/insertoleobject/methods/2
我在这里使用了一个实用的解决方案,当文本文件应该嵌入到 RTF 文档中时,它会起作用。
- 将所需文档另存为 RTF,并在要替换的文本位置添加虚拟文本。
- 使用文本编辑器打开此 RTF,并将
\par
行替换为替换标记[!!! replace me !!!]
。
发件人:
... prefix rtf stuff ...
\par text foo
\par bar text
\par text baz
... suffix rtf stuff ...
收件人:
... prefix rtf stuff ...
[!!! replace me !!!]
... suffix rtf stuff ...
- 另存为template.rtf
- 在 C# 中,读取要嵌入到字符串中的文本文件,每行前面加上
\par<space>
。将模板读入第二个字符串,然后用第一个字符串替换标记。 - 另存为new.rtf。
这是一个示例(抱歉,仅适用于 Perl,C# 也应该是 10 行):
#!/usr/bin/perl
use strict;
my $contents = "";
my $first = 1;
while(<>) {
if (!$first) {
$contents .= "\par ".$_;
} else {
$contents .= $_;
$first = 0;
}
}
my $file = 'template.rtf';
open my $fh, '<', $file or die;
$/ = undef;
my $data = <$fh>;
close $fh;
$data =~ s/\[!!! replace me !!!\]/$contents/g;
print $data;
这样称呼它:
perl mkrtf.pl <test.lst >test.rtf