Всякий раз, когда вы пытаетесь извлечь текст (простой или с информацией о стилизации) из PDF с помощью PDFBox, вам обычно следует начать использовать класс PDFTextStripper
или один из его родственников. Этот класс уже выполняет весь тяжелый подъем, связанный с анализом содержимого PDF.
Вы используете обычный PDFTextStripper
класс как это:
PDDocument document = ...;
PDFTextStripper stripper = new PDFTextStripper();
// set stripper start and end page or bookmark attributes unless you want all the text
String text = stripper.getText(document);
Это возвращает только простой текст, например, от какой-R40 формы:
Claim for repayment of tax deducted
from savings and investments
How to fill in this form
Please fill in this form with details of your income for the
above tax year. The enclosed Notes will help you (but there is
not a note for every box on the form). If you need more help
with anything on this form, please phone us on the number
shown above.
If you are not a UK resident, do not use this form – please
contact us.
Please do not send us any personal records, or tax
certificates or vouchers with your form. We will contact
you if we need these.
Please allow four weeks before contacting us about your
repayment. We will pay you as quickly as possible.
Use black ink and capital letters
Cross out any mistakes and write the
correct information below
...
Вы можете, с другой стороны, перезаписать его метод writeString(String, List<TextPosition>)
и обрабатывать больше информации, чем просто текст. Для того, чтобы добавить информацию о названии используемого шрифта везде, где изменения шрифта, вы можете использовать это:
PDFTextStripper stripper = new PDFTextStripper() {
String prevBaseFont = "";
protected void writeString(String text, List<TextPosition> textPositions) throws IOException
{
StringBuilder builder = new StringBuilder();
for (TextPosition position : textPositions)
{
String baseFont = position.getFont().getBaseFont();
if (baseFont != null && !baseFont.equals(prevBaseFont))
{
builder.append('[').append(baseFont).append(']');
prevBaseFont = baseFont;
}
builder.append(position.getCharacter());
}
writeString(builder.toString());
}
};
По той же форме вы получите
[DHSLTQ+IRModena-Bold]Claim for repayment of tax deducted
from savings and investments
How to fill in this form
[OIALXD+IRModena-Regular]Please fill in this form with details of your income for the
above tax year. The enclosed Notes will help you (but there is
not a note for every box on the form). If you need more help
with anything on this form, please phone us on the number
shown above.
If you are not a UK resident, do not use this form – please
contact us.
[DHSLTQ+IRModena-Bold]Please do not send us any personal records, or tax
certificates or vouchers with your form. We will contact
you if we need these.
[OIALXD+IRModena-Regular]Please allow four weeks before contacting us about your
repayment. We will pay you as quickly as possible.
Use black ink and capital letters
Cross out any mistakes and write the
correct information below
...
Если вы не хотите информация о шрифтах, которая должна быть объединена с текстом, просто создаст отдельные структуры в вашем методе перезаписи.
TextPosition
предлагает гораздо больше информации о части текста, которую он представляет. Осмотрите его!