如何使PDFTextStripper V2.0兼容V1.8的文本提取格式?
I totally get how frustrating it is when upgrading a library breaks the text formatting you rely on—especially that missing space between your shipment number and "Carrier" in the 2.0 output. Let’s walk through the best ways to get 2.0 behaving like 1.8 for text extraction:
1. Use Old-Style Spacing (Quickest Fix)
PDFBox 2.0 revamped how it calculates spacing between characters for better accuracy, but it includes a built-in flag to revert to 1.8’s logic. Just add this line to your PDFTextStripper setup:
PDFTextStripper stripper = new PDFTextStripper(); stripper.setUseOldStyleSpacing(true); // Enables 1.8-style spacing calculation String extractedText = stripper.getText(yourPdfDocument);
This should immediately fix most spacing discrepancies like the one in your example, since it directly mimics the algorithm 1.8 used to decide when to insert spaces between glyphs.
2. Tweak Spacing Tolerance
If the old-style flag doesn’t cover all cases, you can adjust the spacing tolerance. PDFBox 2.0 uses a default tolerance of 0.5f, but 1.8 used a higher value (around 1.0f) which made it more aggressive about inserting spaces. Try this:
stripper.setSpacingTolerance(1.0f); // Matches 1.8's default tolerance
This makes the stripper treat smaller gaps between characters as word breaks, which might align better with your 1.8 output.
3. Build a Custom Stripper (For Edge Cases)
If you still have specific discrepancies, you can subclass PDFTextStripper and override key methods to replicate 1.8’s exact behavior. For example, overriding the spacing calculation method:
public class LegacyTextStripper extends PDFTextStripper { public LegacyTextStripper() throws IOException { super(); } @Override protected float getSpacing(TextPosition previous, TextPosition current) { // Replicate PDFBox 1.8's spacing calculation return current.getXDirAdj() - (previous.getXDirAdj() + previous.getWidthDirAdj()); } }
Then use this custom class instead of the standard PDFTextStripper for your extraction.
4. Test with Your Exact PDF
Every PDF is unique, so make sure to test these changes against your specific document. Start with the setUseOldStyleSpacing(true) method—it’s the simplest and most likely to solve your immediate spacing issue.
内容的提问来源于stack exchange,提问作者Jackie Dong

