要使用此处提供的答案生成高质量的PDF文档,应在完成
Writer
之前计算写入字节的长度,因为它应该是w.write("%%EOF\n")
之前的值。
如何读取写入字节的长度答案中第
w.write("xref\n")
行之前?
Writer
不支持这一点。由于您使用的编码非常简单(ISO-8859-1
),您可以自己计算,因为它相当于写入的字符数。
但这是一个更通用的解决方案:
public class StreamCounter extends FilterOutputStream {
private int written;
public StreamCounter(OutputStream out) {
super(out);
}
public int getWritten() {
return written;
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
super.write(buffer, offset, length);
written += length;
}
@Override
public void write(int oneByte) throws IOException {
super.write(oneByte);
written++;
}
}
然后这样使用它:
try {
StreamCounter streamCount = new StreamCounter(fss.openOutputStream(pdfPath));
try (Writer w = new OutputStreamWriter(streamCount)) {
// same code as before
w.flush();
int bytesWritten = streamCount.getWritten();
// ...
}
} catch(IOException err) {
Log.e(e);
}