-1

我能够将 JTextArea unicode (devanagari) 内容加载/保存到文件中。我想将内容打印到 pdf 文件,所以我使用 iTextPDF api。我的代码片段如下,它打印空文件而不是内容。

package i18n;

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;



public class MyNumbers extends JFrame {
    private ResourceBundle rb;
    private Font devanagariFont;

    public MyNumbers (String language, String fontFile) {
        loadResourceBundle(language);
        loadFont(fontFile);
        display();
    }

    TextArea txtArea;

    private void display() {
        String unicode = null;

        JPanel labels = new JPanel(new GridLayout(0,2));
        JLabel uni = null;
        for(int i=0; i<=10; i++) {
            unicode = rb.getString("" +i);
            labels.add(new JLabel("" + i));
            labels.add(uni = new JLabel(unicode));
            //uni.setFont(devanagariFont);
        }
        labels.add(new JLabel("Time"));
        labels.add(new ClockLabel());
        getContentPane().setLayout(new FlowLayout());
        Box b = Box.createVerticalBox();
        b.add(labels);
        b.add(txtArea = new TextArea(10, 40));
        getContentPane().add(b);
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowOpened(WindowEvent e) {
                // TODO Auto-generated method stub
                try {
                    getInputContext().selectInputMethod(new Locale("hi", "IN"));
                    read();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

            @Override
            public void windowClosing(WindowEvent e) {
                // TODO Auto-generated method stub
                try {
                    System.out.println(getInputContext().getLocale());
                    save();
                    print();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                System.exit(0);

            }


        });
        //setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);



    }


    String fileName = "MyNumbers.txt";
    private void save() throws IOException {
        File f = new File(fileName);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-16"));
        String txt = txtArea.getText();
        writer.write(txt);
        writer.flush();
        writer.close();
    }

    private void read() throws IOException {
        File f = new File(fileName);
        if(f.exists() == false) return;
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
        String line = null;
        while((line = reader.readLine()) != null) {
            txtArea.append(line + "\n");
        }
        reader.close();
    }

    private void loadFont(String fontFile) {
        try {
            InputStream input = getClass().getResourceAsStream(fontFile);
            Font b = Font.createFont(Font.TRUETYPE_FONT, input);
            devanagariFont = b.deriveFont(Font.PLAIN, 11);

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void loadResourceBundle(String language) {
        String base = getClass().getName() + "rb";
        rb = ResourceBundle.getBundle(base, new Locale(language));

    }

    static class ClockLabel extends JLabel implements ActionListener {


        private ClockLabel() {
            new Timer(1000, this).start();
        }



        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        public void actionPerformed(ActionEvent e) {
            Calendar cal = Calendar.getInstance();
            setText(sdf.format(cal.getTime()));

        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyNumbers("hi", "Devnew.ttf");      
            }
        });

    }

    String pdfFileName = "MyNumbers.pdf";
    private void print() {
        System.out.println("Printing PDF file ..");
        try { 
            Document document = new Document(PageSize.A4);  
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFileName));
            document.open();
            PdfContentByte cb = writer.getDirectContent( );
            PdfGraphics2D g2d = new PdfGraphics2D(cb, PageSize.A4.getWidth(), PageSize.A4.getHeight());
            System.out.println(txtArea.getSize());
            txtArea.print(g2d);
            g2d.dispose();
            document.close ();
        }
        catch(DocumentException de) {
            System.err.println(de.getMessage());
        }
        catch(IOException ioe) {
            System.err.println(ioe.getMessage());
        }
    }

}

输出到控制台:

hi_IN
Printing PDF file ..
java.awt.Dimension[width=300,height=170]

请让我知道修复。假设摇摆 JTextArea 应该能够处理它,我没有为图形设置任何字体。使用 indicim.jar 输入法框架添加了 unicode 支持。根据 Dimension 上方的输出,显示文本区域的大小不为零。

为了进行上述测试,您需要 2 个文件:

indicim.jar并将其放在 jre/lib/ext

MyNumbers.txt - 梵文中的 unicode 内容文件,如下所示,您可以自己在文本区域中键入它,并在关机/启动时保存/加载程序。你把它保存在eclipse的项目目录中。

अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
ऊँ 

将在 Eclipse 项目目录中创建一个 pdf 文件,但现在它是空的。

4

1 回答 1

4

问题是你不打电话:

writer.close()

在您的 PdfWriter 上。在方法的末尾添加该行print()应该可以解决问题。

编辑:

这是一个适用于我的SSCCE(您仍然需要将 iText lib 4.2.0 版添加到您的依赖项中):

import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

public class MyNumbers extends JFrame {
    private Font devanagariFont;

    public MyNumbers(String language, String fontFile) {
        loadResourceBundle(language);
        loadFont(fontFile);
        display();
    }

    TextArea txtArea;

    private void display() {
        String unicode = null;

        JPanel labels = new JPanel(new GridLayout(0, 2));
        JLabel uni = null;
        for (int i = 0; i <= 10; i++) {
            unicode = String.valueOf(i);
            labels.add(new JLabel("" + i));
            labels.add(uni = new JLabel(unicode));
            // uni.setFont(devanagariFont);
        }
        labels.add(new JLabel("Time"));
        labels.add(new ClockLabel());
        getContentPane().setLayout(new FlowLayout());
        Box b = Box.createVerticalBox();
        b.add(labels);
        b.add(txtArea = new TextArea(10, 40));
        getContentPane().add(b);
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowOpened(WindowEvent e) {
                // TODO Auto-generated method stub
                try {
                    getInputContext().selectInputMethod(new Locale("hi", "IN"));
                    read();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

            @Override
            public void windowClosing(WindowEvent e) {
                // TODO Auto-generated method stub
                try {
                    System.out.println(getInputContext().getLocale());
                    save();
                    print();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                System.exit(0);

            }

        });
        // setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);

    }

    String fileName = "MyNumbers.txt";

    private void save() throws IOException {
        File f = new File(fileName);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-16"));
        String txt = txtArea.getText();
        writer.write(txt);
        writer.flush();
        writer.close();
    }

    private void read() throws IOException {
        File f = new File(fileName);
        if (f.exists() == false) {
            return;
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            txtArea.append(line + "\n");
        }
        reader.close();
    }

    private void loadFont(String fontFile) {
        try {
            InputStream input = getClass().getResourceAsStream(fontFile);
            Font b = Font.createFont(Font.TRUETYPE_FONT, input);
            devanagariFont = b.deriveFont(Font.PLAIN, 11);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadResourceBundle(String language) {
        String base = getClass().getName() + "rb";

    }

    static class ClockLabel extends JLabel implements ActionListener {

        private ClockLabel() {
            new Timer(1000, this).start();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        @Override
        public void actionPerformed(ActionEvent e) {
            Calendar cal = Calendar.getInstance();
            setText(sdf.format(cal.getTime()));

        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MyNumbers("hi", "Devnew.ttf");
            }
        });

    }

    String pdfFileName = "MyNumbers.pdf";

    private void print() {
        System.out.println("Printing PDF file ..");
        try {
            File pdf = new File(pdfFileName);
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            Graphics2D g2d = cb.createGraphics(PageSize.A4.getWidth(), PageSize.A4.getHeight());
            System.out.println(txtArea.getSize());
            txtArea.printAll(g2d);
            g2d.dispose();
            document.close();
            writer.flush();
            writer.close();
            Desktop.getDesktop().open(pdf);
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
    }

}
于 2012-09-26T08:16:07.230 回答