本文整理匯總了Java中com.itextpdf.text.DocumentException類的典型用法代碼示例。如果您正苦於以下問題:Java DocumentException類的具體用法?Java DocumentException怎麽用?Java DocumentException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
DocumentException類屬於com.itextpdf.text包,在下文中一共展示了DocumentException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testRemoveSignatureFromPDFSignedFirmaCerta
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
/**
* <a href="http://itext.2136553.n4.nabble.com/trying-to-remove-a-signature-from-pdf-file-tt4660983.html">
* trying to remove a signature from pdf file
* </a>
* <br/>
* <a href="http://itext.2136553.n4.nabble.com/attachment/4660983/0/PDFSignedFirmaCerta.pdf">
* PDFSignedFirmaCerta.pdf
* </a>
* <p>
* Indeed, this code fails with a {@link NullPointerException}. The cause is that a dubious construct
* created by the signature software then is processed by iText code not sufficiently defensively programmed:
* The signature claims to have an annotation on a page but that page does claim not to have any anotations
* at all.
* </p>
*/
@Test
public void testRemoveSignatureFromPDFSignedFirmaCerta() throws IOException, GeneralSecurityException, DocumentException
{
try ( InputStream inputStream = getClass().getResourceAsStream("PDFSignedFirmaCerta.pdf");
OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "PDFSignedFirmaCerta-withoutSig.pdf")))
{
Provider provider = new BouncyCastleProvider();
Security.addProvider(provider);
PdfReader reader = new PdfReader(inputStream, null);
AcroFields af = reader.getAcroFields();
ArrayList<String> names = af.getSignatureNames();
for (String name : names) {
System.out.println("Signature name: " + name);
System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
PdfPKCS7 pk = af.verifySignature(name, provider.getName());
System.out.println("SignatureDate: " + pk.getSignDate());
System.out.println("Certificate: " + pk.getSigningCertificate());
System.out.println("Document modified: " + !pk.verify());
af.removeField(name);
}
PdfStamper stamper = new PdfStamper(reader, outputStream, '\0');
stamper.close();
}
}
示例2: testSwitchOrientation
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
/**
* <a href="http://stackoverflow.com/questions/34394199/i-cant-rotate-my-page-from-existing-pdf">
* I can't rotate my page from existing PDF
* </a>
* <p>
* Switching between portrait and landscape like this obviously will cut off some parts of the page.
* </p>
*/
@Test
public void testSwitchOrientation() throws DocumentException, IOException
{
try (InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/n2013.00849449.pdf"))
{
PdfReader reader = new PdfReader(resourceStream);
int n = reader.getNumberOfPages();
PdfDictionary pageDict;
for (int i = 1; i <= n; i++) {
Rectangle rect = reader.getPageSize(i);
Rectangle crop = reader.getCropBox(i);
pageDict = reader.getPageN(i);
pageDict.put(PdfName.MEDIABOX, new PdfArray(new float[] {rect.getBottom(), rect.getLeft(), rect.getTop(), rect.getRight()}));
pageDict.put(PdfName.CROPBOX, new PdfArray(new float[] {crop.getBottom(), crop.getLeft(), crop.getTop(), crop.getRight()}));
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(RESULT_FOLDER, "n2013.00849449-switch.pdf")));
stamper.close();
reader.close();
}
}
示例3: build
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
/**
* Update NDA file with visitor name and visitor signature.
*
* @param destFile
* @param signatureImage signature file
* @param visitorName
* @return File
*/
public static File build(Path destFile, File signatureImage, String visitorName) {
try {
PdfReader pdfReader = new PdfReader(ndaUrl);
PdfStamper pdfStamper = new PdfStamper(pdfReader,
new FileOutputStream(destFile.toString()));
Image image = createNDAImage(signatureImage, 0, 0);
PdfContentByte over = pdfStamper.getOverContent(5);
over.addImage(image);
PdfContentByte pdfContentByte = pdfStamper.getOverContent(5);
pdfContentByte.beginText();
pdfContentByte.setFontAndSize(BaseFont.createFont
(BaseFont.HELVETICA,
BaseFont.CP1257,
BaseFont.EMBEDDED
)
, 10);
pdfContentByte.setTextMatrix(112, 428);
pdfContentByte.showText(visitorName);
pdfContentByte.setTextMatrix(89, 406);
pdfContentByte.showText(new SimpleDateFormat("E, dd MMM yyyy").format(new Date()));
pdfContentByte.endText();
pdfStamper.close();
return destFile.toFile();
} catch (IOException | DocumentException | NumberFormatException e) {
logger.error("Exception while generating NDA file. ",e);
return null;
}
}
示例4: createPDF
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
public void createPDF(String outputFile, ArrayList<Question> qlist, boolean showCorrectAnswer,
PageCounter pagecounter, int maximumPageNumber, String inputFolder) throws DocumentException, IOException
{
_inputFolder = inputFolder;
Document document = new Document(PageSize.A4, 50, 50, 70, 50);
PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
pdfwriter.setBoxSize("art", new Rectangle(36, 54, 559, 788));
pdfwriter.setPageEvent(new HeaderFooter(maximumPageNumber));
if (pagecounter != null)
{
pdfwriter.setPageEvent(pagecounter);
}
document.open();
Paragraph p = new Paragraph();
// p.setSpacingBefore(SPACING);
p.setSpacingAfter(SPACING);
p.setIndentationLeft(INDENTATION);
writeQuestions(p, document, showCorrectAnswer, qlist);
document.close();
}
示例5: getIdentityFont
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
private BaseFont getIdentityFont(String fontPath,ApplicationContext applicationContext) throws DocumentException,IOException {
if(!fontPath.startsWith(ApplicationContext.CLASSPATH_URL_PREFIX)){
fontPath=ApplicationContext.CLASSPATH_URL_PREFIX+fontPath;
}
String fontName = fontPath;
int lastSlashPos=fontPath.lastIndexOf("/");
if(lastSlashPos!=-1){
fontName = fontPath.substring(lastSlashPos+1,fontPath.length());
}
if (fontName.toLowerCase().endsWith(".ttc")) {
fontName = fontName + ",0";
}
InputStream inputStream=null;
try{
inputStream=applicationContext.getResource(fontPath).getInputStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
BaseFont baseFont = BaseFont.createFont(fontName, BaseFont.IDENTITY_H,BaseFont.EMBEDDED,true,bytes,null);
baseFont.setSubset(true);
return baseFont;
}finally{
if(inputStream!=null)inputStream.close();
}
}
示例6: addTitlePage
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
private static void addTitlePage(Document document,Resolucion res)
throws DocumentException {
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
preface.add(new Paragraph("Consejo Profesional de Informatica de Santiago del Estero", catFont));
addEmptyLine(preface, 1);
// Will create: Report generated by: _name, _date
preface.add(new Paragraph( "Comision Directiva del Consejo, " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
smallBold));
addEmptyLine(preface, 2);
preface.add(new Paragraph("Resolucion N°"+res.getNumero_resolucion()+"",
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph("Esta Resolucion de tipo "+res.getTipo()+" formulada para notificar al socio con legajo: "+res.getLegajo_socio()+" de su actual estado como socio del Consejo.\n"
+ res.getDescripcion_solicitud()+" "+res.getDescripcion_resolucion()+" en la fecha "+res.getFecha(),
cuerpo));
document.add(preface);
// Start a new page
document.newPage();
}
示例7: print
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
public void print(String plot_pdf) {
try {
float width = jframe.getSize().width,
height = jframe.getSize().height;
Document document = new Document(new Rectangle(width, height));
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(plot_pdf));
document.open();
PdfContentByte canvas = writer.getDirectContent();
PdfTemplate template = canvas.createTemplate(width, height);
Graphics2D g2d = new PdfGraphics2D(template, width, height);
jframe.paint(g2d);
g2d.dispose();
canvas.addTemplate(template, 0, 0);
document.close();
} catch (FileNotFoundException | DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
示例8: split
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
public List<byte[]> split(byte[] input) throws IOException, DocumentException {
PdfReader pdfReader = new PdfReader(input);
List<byte[]> pdfFiles = new ArrayList<>();
int pageCount = pdfReader.getNumberOfPages();
int pageIndex = 0;
while (++pageIndex <= pageCount) {
Document document = new Document(pdfReader.getPageSizeWithRotation(pageIndex));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfCopy pdfCopy = new PdfSmartCopy(document, byteArrayOutputStream);
pdfCopy.setFullCompression();
PdfImportedPage pdfImportedPage = pdfCopy.getImportedPage(pdfReader, pageIndex);
document.open();
pdfCopy.addPage(pdfImportedPage);
document.close();
pdfCopy.close();
pdfFiles.add(byteArrayOutputStream.toByteArray());
}
return pdfFiles;
}
示例9: testShowTextAlignedVsSimpleColumnTopAlignment
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
/**
* <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment">
* ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment
* </a>
* <p>
* Indeed, the coordinates do not line up. The y coordinate of
* {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)}
* denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds
* the text to come.
* </p>
*/
@Test
public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf")));
document.open();
Font fontQouteItems = new Font(BaseFont.createFont(), 12);
PdfContentByte canvas = writer.getDirectContent();
// Item Number
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0);
// Estimated Qty
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0);
// Item Description
ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping
ct.setSimpleColumn(new Rectangle(193, 070, 390, 450));
ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems));
ct.go();
document.close();
}
示例10: generateFileAction
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
@FXML
public void generateFileAction(ActionEvent actionEvent) {
FileChooser saveChooser = new FileChooser();
Window stage = ((Node) actionEvent.getSource()).getScene().getWindow();
saveChooser.setTitle("Zapisz plik");
saveChooser.setInitialDirectory(new File(System.getProperty("user.home")));
saveChooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("PDF file", "*.pdf"));
saveChooser.setInitialFileName("faktura.pdf");
File file = saveChooser.showSaveDialog(stage);
if (file != null) {
try {
updateData();
model.setInvoiceData(invoiceData);
model.setReceiverData(receiverData);
model.setSenderData(senderData);
model.generatePDF(file);
} catch (IOException | DocumentException e) {
Dialog dialog = new Dialog<>();
dialog.getDialogPane().getButtonTypes().add(new ButtonType("Ok", ButtonBar.ButtonData.OK_DONE));
dialog.setContentText("Wystąpił błąd podczas próby zapisu");
dialog.showAndWait();
}
}
}
示例11: downloadNotebook
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
@RequestMapping(value = "/exportNotebook")
public ResponseEntity<byte[]> downloadNotebook(@RequestParam(value = "type") String type, @RequestParam(value = "notebookId") int notebookId, HttpSession session) throws IOException, DocumentException{
String leftPath = session.getServletContext().getRealPath("/temp/");
//在服務器端生成zip文件
File file = downloadService.downloadNotebook(notebookId, type, leftPath);
//將文件返回給用戶
HttpHeaders headers = downloadService.genHttpHeaders(notebookId, type, "notebook");
ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
file.delete();
return result;
}
示例12: downloadNote
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
public File downloadNote(int noteId, String type, String leftPath)throws IOException, DocumentException {
Note note = noteDao.getNoteById(noteId);
String currentVersion = note.getHistory().get(note.getVersionPointer());
JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject();
String content = obj.get("content").getAsString();
String htmlPath = leftPath + "htmlTemp.html";
File file = new File(htmlPath);
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("<body>" + content + "</body>");
writer.close();
if(type.equals("pdf")) {
String pdfPath = leftPath + "pdfTemp.pdf";
File pdfFile = new File(pdfPath);
exportUtil.htmlToPdf(htmlPath, pdfFile);
file.delete();
file = pdfFile;
}
//default html
return file;
}
示例13: downloadNotebook
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
public File downloadNotebook(int notebookId, String type, String leftPath) throws IOException,DocumentException{
File tempDir = new File(leftPath + "tempDir");
String tempPath = leftPath + "tempDir/";
tempDir.mkdirs();
ArrayList<Integer> notes = notebookDao.getNotebookById(notebookId).getNotes();
for(int noteId : notes){
Note note = noteDao.getNoteById(noteId);
String currentVersion = note.getHistory().get(note.getVersionPointer());
JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject();
String content = obj.get("content").getAsString();
String htmlPath = tempPath + noteId +".html";
File file = new File(htmlPath);
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("<body>" + content + "</body>");
writer.close();
if(type.equals("pdf")) {
String pdfPath = tempPath + noteId +".pdf";
File pdfFile = new File(pdfPath);
exportUtil.htmlToPdf(htmlPath, pdfFile);
file.delete();
}
}
return exportUtil.compressExe(tempDir, leftPath + "temp.zip");
}
示例14: onEndPage
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
/**
* Adds a header to every page
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
* com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
*/
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(3);
try {
table.setWidths(new int[]{40,5,10});
table.setTotalWidth(100);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
Font font=new Font(chineseFont,8);
font.setColor(new BaseColor(55,55,55));
Paragraph paragraph=new Paragraph("第 "+writer.getPageNumber()+" 頁 共",font);
paragraph.setAlignment(Element.ALIGN_RIGHT);
table.addCell(paragraph);
Image img=Image.getInstance(total);
img.scaleAbsolute(28, 28);
PdfPCell cell = new PdfPCell(img);
cell.setBorder(Rectangle.NO_BORDER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
PdfPCell c = new PdfPCell(new Paragraph("頁",font));
c.setHorizontalAlignment(Element.ALIGN_LEFT);
c.setBorder(Rectangle.NO_BORDER);
table.addCell(c);
float center=(document.getPageSize().getWidth())/2-120/2;
table.writeSelectedRows(0, -1,center,30, writer.getDirectContent());
}
catch(DocumentException de) {
throw new ExceptionConverter(de);
}
}
示例15: writeJChartToFile
import com.itextpdf.text.DocumentException; //導入依賴的package包/類
static String writeJChartToFile(JFreeChart chart, File file, FileTypes fileType) throws IOException, DocumentException {
String fileName = file.getPath();
switch (fileType) {
case svg:
Tools.exportChartAsSVG(chart, new Rectangle(1000, 1000), file);
break;
case pdf:
Tools.exportChartAsPDF(chart, new Rectangle(500, 400), file);
break;
case jchart:
break;
case csv:
Tools.exportChartAsCSV(chart, file);
break;
default:
ChartUtilities.saveChartAsPNG(file, chart, 1000, 1000);
break;
}
return fileName;
}