我需要读取带有文件路径“C:\ file.pdf”的pdf文件并将其写入outputStream。最简单的方法是什么?
@Controller
public class ExportTlocrt {
@Autowired
private PhoneBookService phoneBookSer;
private void setResponseHeaderTlocrtPDF(HttpServletResponse response) {
response.setContentType("application/pdf");
response.setHeader("content-disposition", "attachment; filename=Tlocrt.pdf" );
}
@RequestMapping(value = "/exportTlocrt.html", method = RequestMethod.POST)
public void exportTlocrt(Model model, HttpServletResponse response, HttpServletRequest request){
setResponseHeaderTlocrtPDF(response);
File f = new File("C:\\Tlocrt.pdf");
try {
OutputStream os = response.getOutputStream();
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
os.write(buf, 0, c);
os.flush();
}
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
............................................... ............................................
答案 0 :(得分:29)
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
迄今为止最简单的方法。希望这会有所帮助。
答案 1 :(得分:10)
您可以使用Apache中的PdfBox,它易于使用且性能良好。
以下是从PDF文件中提取文本的示例(您可以阅读更多here):
import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;
public class PDFTest {
public static void main(String[] args){
PDDocument pd;
BufferedWriter wr;
try {
File input = new File("C:\\Invoice.pdf"); // The PDF file from where you would like to extract
File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
pd = PDDocument.load(input);
System.out.println(pd.getNumberOfPages());
System.out.println(pd.isEncrypted());
pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
PDFTextStripper stripper = new PDFTextStripper();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
stripper.writeText(pd, wr);
if (pd != null) {
pd.close();
}
// I use close() to flush the stream.
wr.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
<强>更新强>
您可以使用PDFTextStripper获取文字:
PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created