简体   繁体   English

无法使用Java剥离pdf中的页面行

[英]unable to strip page lines in pdf using java

i want to strip 1st page and 3rd page but why does it is stripping only 1st page and displaying same output twice.I am using pdfbox here.It is unable to strip 3rd page even though i have written it as stripper.setStartPage( 3 ) 我想剥离第一页和第三页,但为什么它只剥离第一页并显示两次相同的输出。我在这里使用pdfbox。即使我将其写为stripper.setStartPage(3),也无法剥离第三页

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class GetlinesFromPDF extends PDFTextStripper {

    static List<String> lines = new ArrayList<String>();    
    public GetlinesFromPDF() throws IOException {
    }

    public static void main( String[] args ) throws IOException    {
        PDDocument document = null;
        String fileName = "C://Users//policy.pdf"; 
        try {
            document = PDDocument.load( new File(fileName) );
            PDFTextStripper stripper = new GetlinesFromPDF();                             
            stripper.setSortByPosition( true );


            stripper.setStartPage( 1 );
            stripper.setEndPage( 1);
            Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
            stripper.writeText(document, dummy);
             String qoute_number = lines.get(2);
            System.out.println(qoute_number);

            stripper.setStartPage( 3 );
            stripper.setEndPage( 3);
            Writer dummy1 = new OutputStreamWriter(new ByteArrayOutputStream());
            stripper.writeText(document, dummy1);
            String qoute_number1 = lines.get(2);
            System.out.println(qoute_number1);       
        }

        finally {
            if( document != null ) {
                document.close();
            }
        }
    }

    @Override
    protected void writeString(String str, List<TextPosition> textPositions) throws IOException {
     lines.add(str);

}}

The stripping works perfectly. 剥离工作完美。 Your problem is that lines adds all your results - stripping of page one and page three. 您的问题是, lines会添加所有结果-剥离第一页和第三页。 Therefore, printing out the same index ( get(2) ) always contains content from page one. 因此,打印出相同的索引( get(2) )始终包含第一页的内容。 If you add a clear call between the two strippings, you should see the correct result. 如果在两个剥离之间添加清晰的调用,则应该看到正确的结果。

stripper.setStartPage( 1 );
stripper.setEndPage( 1);
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
String qoute_number = lines.get(2);
System.out.println(qoute_number);

lines.clear();

stripper.setStartPage( 3 );
stripper.setEndPage( 3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM