【问题标题】:COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?COSStream 已关闭,无法读取。也许其封闭的 PDDocument 已关闭?
【发布时间】:2020-05-19 00:51:27
【问题描述】:

基本上,我正在尝试在 Java 中创建一个小工具,在其中我从某种用户输入中获取文本,考虑一个普通的文本框,然后用它创建一个 PDF 文件。

到目前为止,我设法用我对 PDFBox 的基本知识非常快速地抓取了一些东西。

在我的应用程序中,我正在使用 GUI 元素在另一个类中实例化这个类(如下所示),如果我输入文本,假设是一个文本框,并运行这个 PDFLetter 脚本一次 - 它就像一个魅力但再次运行它,它崩溃并给我这个恼人的错误:

COSStream 已关闭,无法读取。也许它是封闭的 PDDocument 已关闭?

我真的看不出有任何方法可以在我的代码中触发此错误。我认为这与我的基本“跳转到下一页”解决方案有关,但它在当前状态下工作,所以我不知道该相信什么了。

我实例化类的方式,如果你需要知道,是这样的:

PDFLetter.PDFLetterGenerate(textInput.getValue().toString());   

此外,我认为触发问题的一定是垃圾收集的某种问题,但我不再认为是这种情况。

public class PDFLetter {
    private static final int PAGE_MARGIN = 80;

    static float TABLE_HEIGHT;  

    static Boolean newPage = false;

public static String text = // null;
        "Ding Dong ding dong Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et "
        + "Imperdiet dui accumsan sit amet. Risus in hendrerit gravida rutrum quisque non tellus orci ac.";

static List<String> textList = new ArrayList<String>();

PDDocument document = new PDDocument();
static PDPage main_page = new PDPage();
static PDPage new_page = new PDPage(); 

static File file = new File("C:/PDFTests/temp.pdf"); 

public void PDFLetterGenerate (String args) throws Exception {
    text = args;
    text = text.replace("\n", "").replace("\r", "");

    if(file.exists()) file.delete();
    file.createNewFile();
    //Creating PDF document object 
    PDDocument document = new PDDocument();       
    document.addPage(main_page);  
    mainBody(document, main_page);      
    document.addPage(new_page);                          
    if(!newPage) document.removePage(new_page);

    document.save(file);
    document.close(); 
}

public static void mainBody(PDDocument doc, PDPage page) throws Exception { 
        final float width = page.getMediaBox().getWidth()-(2*PAGE_MARGIN);
        int fontSize = 11;
        float leading = 1.5f * fontSize;
        final float max = 256;
        PDFont pdfFont = PDType1Font.HELVETICA;

        @SuppressWarnings("deprecation")
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        int lastSpace = -1;
        while (text.length() > 0){
            int spaceIndex = text.indexOf(' ', lastSpace + 1);
            if (spaceIndex < 0) spaceIndex = text.length();
            String subString = text.substring(0, spaceIndex);
            float size = fontSize * pdfFont.getStringWidth(subString) / 1000;

            if (size > width){
                if (lastSpace < 0) lastSpace = spaceIndex;
                subString = text.substring(0, lastSpace);
                textList.add(subString);
                text = text.substring(lastSpace).trim();
                lastSpace = -1;
            }

            else if (spaceIndex == text.length()){
                textList.add(text);
                text = "";
            }

            else{
                lastSpace = spaceIndex;
            }
        }

        contentStream.beginText();
        contentStream.setFont(pdfFont, fontSize);
        contentStream.newLineAtOffset(PAGE_MARGIN, TABLE_HEIGHT);


        @SuppressWarnings("deprecation")
        PDPageContentStream newStream = new PDPageContentStream(doc, new_page, true, true);

        int nextPage_i = 0;

        for (int i=0; i<textList.size(); i++)//String line: textList){
            System.out.println("HEIGHT: "+ TABLE_HEIGHT);
            nextPage_i = i;
            String line = textList.get(i);
            float charSpacing = 0;

            if (line.length() > 1){         
                float size = fontSize * pdfFont.getStringWidth(line) / 1000;
                float free = width - size;
                if (free > 0){
                    charSpacing = free / (line.length() - 1);
                }
                TABLE_HEIGHT = TABLE_HEIGHT - 10;
            }

            contentStream.setCharacterSpacing(charSpacing); 
            contentStream.showText(line);
            contentStream.newLineAtOffset(0, -leading);

            if(TABLE_HEIGHT <= 280){  
                contentStream.endText();  
                contentStream.close(); 
                newPage = true;
                break; 
            } 
        } 

        if(!newPage){
            contentStream.endText();  
            contentStream.close(); 
        }

        else if (newPage){          
            float NEW_HEIGHT = 600;             
            newStream.beginText();
            newStream.setFont(pdfFont, fontSize);
            newStream.newLineAtOffset(PAGE_MARGIN, NEW_HEIGHT);

            for (int j=nextPage_i; j<textList.size(); j++)//String line: textList){
                System.out.println("HEIGHT: "+ NEW_HEIGHT);
                nextPage_i = j;
                String line = textList.get(j);
                float charSpacing = 0;

                if (line.length() > 1){         
                    float size = fontSize * pdfFont.getStringWidth(line) / 1000;
                    float free = width - size;
                    if (free > 0)
                    {
                        charSpacing = free / (line.length() - 1);
                    }
                    NEW_HEIGHT = NEW_HEIGHT - 10; 
                }
                newStream.setCharacterSpacing(charSpacing); 
                newStream.showText(line);
                newStream.newLineAtOffset(0, -leading);
            }
            newStream.endText();  
            newStream.close();
        }
        lastSpace = -1;
    }

【问题讨论】:

    标签: java pdf-generation pdfbox


    【解决方案1】:

    PDPage 实例化拉入PDFLetterGenerate

    public void PDFLetterGenerate (String args) throws Exception {
        PDPage main_page = new PDPage();
        PDPage new_page = new PDPage(); 
    
        text = args;
        text = text.replace("\n", "").replace("\r", "");
    
        if(file.exists()) file.delete();
        file.createNewFile();
        //Creating PDF document object 
        PDDocument document = new PDDocument();       
        document.addPage(main_page);  
        mainBody(document, main_page);      
        document.addPage(new_page);                          
        if(!newPage) document.removePage(new_page);
    
        document.save(file);
        document.close(); 
    }
    

    在您的代码中,页面被实例化一次,并且在第一次运行 PDFLetterGenerate 后关闭底层流,而本地 PDDocument document 在添加页面后关闭。

    此外,还将new_page 设为mainBody 的参数,而不是依靠静态变量来保存它。

    您的代码中还有许多其他问题,但上述更改应该可以帮助您入门。

    【讨论】:

    • 祝福你,这是一个愚蠢的问题,但有时我猜每个人都会被这样难住。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2013-08-17
    • 2012-11-10
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2019-04-16
    相关资源
    最近更新 更多