【发布时间】:2016-11-23 10:37:14
【问题描述】:
我有一个来自 iTextSharp 的结果,它可以通过 pdf 阅读器进行解析,但我希望能够获取二进制内容并手动解析它。我试过在标签<</Length 256/Filter/FlateDecode>>stream之间取文本
和
endstream并使用 .NET DeflateStream 类尝试解压缩导致此异常的文本:
System.IO.InvalidDataException: Block length does not match with its complement. at System.IO.Compression.Inflater.DecodeUncompressedBlock(Boolean& end_of_block) at System.IO.Compression.Inflater.Decode() at System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length) at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count) at System.IO.Stream.InternalCopyTo(Stream destination, Int32 bufferSize) at FlateDecodeTest.Decompress(Byte[] data)
我的代码是:
using System;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
public class FlateDecodeTest
{
public static void Main()
{
string s = @"xœuÁN!E÷|Å...";
byte[] b = Decompress(GetBytes(s));
Console.WriteLine(GetString(b));
}
public static byte[] Decompress(byte[] data)
{
Console.WriteLine(data.Length);
byte[] decompressedArray = null;
try
{
using (MemoryStream decompressedStream = new MemoryStream())
{
using (MemoryStream compressStream = new MemoryStream(data))
{
using (DeflateStream deflateStream = new DeflateStream(compressStream, CompressionMode.Decompress))
{
deflateStream.CopyTo(decompressedStream);
}
}
decompressedArray = decompressedStream.ToArray();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
return decompressedArray;
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
}
【问题讨论】:
-
“获取标签
<</Length 256/Filter/FlateDecode>>stream和endstream之间的文本” - 这不是那里的文本,它的二进制数据。如果您从那里获取数据作为文本,您很可能已经损坏了它。如果纯属运气没有发生这种损坏,您的GetBytes方法会尝试完全混淆数据。使用流内容中的确切字节。