本文整理汇总了Java中com.itextpdf.text.Image.scaleToFit方法的典型用法代码示例。如果您正苦于以下问题:Java Image.scaleToFit方法的具体用法?Java Image.scaleToFit怎么用?Java Image.scaleToFit使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.itextpdf.text.Image
的用法示例。
在下文中一共展示了Image.scaleToFit方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createPdf
import com.itextpdf.text.Image; //导入方法依赖的package包/类
public void createPdf(String filename) throws DocumentException, IOException {
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
// TODO: force iText to respect the order in which content is added
writer.setStrictImageSequence(true);
document.open();
// step 4 - add content into document
String[] imageNames = { "35_Cal_Crutchlow.jpg", "38_Bradley_Smith.jpg", "46_Valentino_Rossi.jpg",
"99_Jorge_Lorenzo.jpg" };
for (int i = 0; i < 4; i++) {
Image image = Image.getInstance("resources/img/" + imageNames[i]);
// TODO: scale image
image.scaleToFit(500, 500); // scale size
document.add(image);
document.add(new Paragraph(imageNames[i]));
}
document.close();
}
示例2: addImage
import com.itextpdf.text.Image; //导入方法依赖的package包/类
/**
* adds an image to the document.
*
* @param doc
* @param iji
* @return
* @throws InterruptedException
* @throws ExecutionException
* @throws IOException
* @throws DocumentException
*/
public Document addImage(Document doc, ImageJobDescription iji)
throws InterruptedException, ExecutionException, IOException,
DocumentException {
// create image worker
ImageWorker job = new ImageWorker(dlConfig, iji);
// submit
Future<DocuImage> jobTicket = imageJobCenter.submit(job);
// wait for result
DocuImage img = jobTicket.get();
// scale the image
Image pdfimg = Image.getInstance(img.getAwtImage(), null);
float docW = PageSize.A4.getWidth() - 2 * PageSize.A4.getBorder();
float docH = PageSize.A4.getHeight() - 2 * PageSize.A4.getBorder();
// fit the image to the page
pdfimg.scaleToFit(docW, docH);
// add to PDF
doc.add(pdfimg);
return doc;
}
示例3: savePageAsPdf
import com.itextpdf.text.Image; //导入方法依赖的package包/类
public String savePageAsPdf(boolean scaled) throws IOException, DocumentException
{
String pdfName = "";
// Define test screenshot root
String test = "";
if (TestNamingUtil.isTestNameRegistered()) {
test = TestNamingUtil.getTestNameByThread();
} else {
test = "undefined";
}
File testRootDir = ReportContext.getTestDir();
File artifactsFolder = ReportContext.getArtifactsFolder();
String fileID = test.replaceAll("\\W+", "_") + "-" + System.currentTimeMillis();
pdfName = fileID + ".pdf";
String fullPdfPath = artifactsFolder.getAbsolutePath() + "/" + pdfName;
// TODO: test this implementation and change back to capture if necessary
Image image = Image.getInstance(testRootDir.getAbsolutePath() + "/" + Screenshot.captureFailure(driver, ""));
Document document = null;
if (scaled)
{
document = new Document(PageSize.A4, 10, 10, 10, 10);
if (image.getHeight() > (document.getPageSize().getHeight() - 20)
|| image.getScaledWidth() > (document.getPageSize().getWidth() - 20))
{
image.scaleToFit(document.getPageSize().getWidth() - 20, document.getPageSize().getHeight() - 20);
}
} else
{
document = new Document(new RectangleReadOnly(image.getScaledWidth(), image.getScaledHeight()));
}
PdfWriter.getInstance(document, new FileOutputStream(fullPdfPath));
document.open();
document.add(image);
document.close();
return fullPdfPath;
}
示例4: comicFolderToPDF
import com.itextpdf.text.Image; //导入方法依赖的package包/类
/**
* 將排序過的圖片轉成PDF
*
* @param pageSize
* pdf的文件大小:A4 or B3 etc...
* @param sourceFolderPath
* 圖片所在的資料夾路徑
* @param pathList
* 排序過的圖片列表
* @param targetPdfPath
* 要儲存的的PDF路徑
* @return
* @throws Exception
*/
public static boolean comicFolderToPDF(Rectangle pageSize,
String sourceFolderPath, ArrayList<String> pathList,
String targetPdfPath) throws Exception {
boolean result = false;
Document document = new Document(pageSize);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(targetPdfPath));
writer.setPageEvent(new HeaderFooter(14));
document.open();
for (String filename : pathList) {
String filePath = sourceFolderPath + File.separator + filename;
document.newPage();
Image img = Image.getInstance(filePath);
img.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight());
img.setBorderColor(BaseColor.WHITE);
document.add(img);
}
result = true;
document.close();
return result;
}
示例5: dataTableTitile
import com.itextpdf.text.Image; //导入方法依赖的package包/类
private void dataTableTitile(Document documento, String data) throws IOException, BadElementException, DocumentException {
try {
pTableEmpresaPricipal = new PdfPTable(new float[]{15f, 85f});
pTableEmpresaInforImpres1 = new PdfPTable(1);
pTableEmpresaInforImpres5 = new PdfPTable(1);
PdfPCell pCellNomeEmpresa = new PdfPCell(new Phrase(Empresa.NOME, fontCabecalhoNG));
pCellNomeEmpresa.setBorder(0);
PdfPCell pCellNomeEndereco = new PdfPCell(new Phrase(Empresa.ENDERECO, fontCabecalhoN));
pCellNomeEndereco.setBorder(0);
PdfPCell pCellCaixaPostal = new PdfPCell(new Phrase(Empresa.CAIXAPOSTAL, fontCabecalhoN));
pCellCaixaPostal.setBorder(0);
PdfPCell pCellTeleFax = new PdfPCell(new Phrase(Empresa.TELEFAX + " " + ConfigDoc.Empresa.EMAIL, fontCabecalhoN));
pCellTeleFax.setBorder(0);
PdfPCell pCellSociedade = new PdfPCell(new Phrase(Empresa.SOCIEDADE, fontCabecalhoN));
pCellSociedade.setBorder(0);
Image imageEmpresa = Image.getInstance("logo.png");
imageEmpresa.scaleToFit(120f, 85f);
pTableEmpresaInforImpres1.addCell(pCellNomeEmpresa);
pTableEmpresaInforImpres1.addCell(pCellNomeEndereco);
pTableEmpresaInforImpres1.addCell(pCellCaixaPostal);
pTableEmpresaInforImpres1.addCell(pCellTeleFax);
pTableEmpresaInforImpres1.addCell(pCellSociedade);
PdfPCell cellTabela3 = new PdfPCell(pTableEmpresaInforImpres1);
cellTabela3.setBorder(0);
pTableEmpresaInforImpres5.addCell(cellTabela3);
PdfPCell cellTabela5 = new PdfPCell(pTableEmpresaInforImpres5);
cellTabela5.setBorder(0);
PdfPCell cellTabela6 = new PdfPCell(imageEmpresa);
cellTabela6.setBorder(0);
pTableEmpresaPricipal.setWidthPercentage(95);
pTableEmpresaPricipal.addCell(cellTabela6);
pTableEmpresaPricipal.addCell(cellTabela5);
PdfPTable pTableTitulo = new PdfPTable(1);
pTableTitulo.setHorizontalAlignment(Element.ALIGN_CENTER);
pTableTitulo.setWidthPercentage(100);
SimpleDateFormat sdfEsp = new SimpleDateFormat("MMMM, yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy");
PdfPCell cellTitulo = new PdfPCell(new Phrase("TOTAL PREMIUM COLLECTED ON TRAVEL INSURANCE AND TAXES FOR "+sdfEsp.format(sdf.parse(data)).toUpperCase(), fontCorpoNG));
cellTitulo.setBorder(0);
cellTitulo.setPaddingBottom(10f);
pTableTitulo.addCell(cellTitulo);
pTableEmpresaPricipal.setHorizontalAlignment(Element.ALIGN_CENTER);
documento.add(pTableEmpresaPricipal);
documento.add(pTableNull);
documento.add(pTableTitulo);
} catch (ParseException ex) {
Logger.getLogger(ExporOnlyViagemPdf.class.getName()).log(Level.SEVERE, null, ex);
}
}
示例6: tiff2Pdf
import com.itextpdf.text.Image; //导入方法依赖的package包/类
public void tiff2Pdf(File singleTifFile, File pdfFile) {
// based on tiff2pdf from itext toolbox 0.0.2
// (cfr.http://itexttoolbox.sourceforge.net/doku.php?id=download&DokuWiki=
// ecde1bfec0b8cca87dd8c6c042183992)
try {
RandomAccessFileOrArray ra = new RandomAccessFileOrArray(
singleTifFile.getAbsolutePath());
// RandomAccessFileOrArray ra = new
// RandomAccessFileOrArray(tempByteArray);
int comps = TiffImage.getNumberOfPages(ra);
Document document = new Document(PageSize.A4);
float width = PageSize.A4.getWidth();
float height = PageSize.A4.getHeight();
Image img = TiffImage.getTiffImage(ra, 1);
document.setPageSize(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdfFile));
// pdf/a
// from
// http://www.opensubscriber.com/message/[email protected]
// .net/7593470.html
// check that it is really pdf/a:
// http://www.intarsys.de/produkte/pdf-a-live/pdf-a-check-1
// => 2 warnings
// Keine eindeutige ID gefunden
// Kein History-Eintrag vorhanden
writer.setPDFXConformance(PdfWriter.PDFA1B);
document.open();
PdfDictionary outi = new PdfDictionary(PdfName.OUTPUTINTENT);
outi.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(
"sRGB IEC61966-2.1"));
outi.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
outi.put(PdfName.S, PdfName.GTS_PDFA1);
ICC_Profile icc = ICC_Profile.getInstance(Thread.currentThread()
.getContextClassLoader().getResourceAsStream(
"/srgb.profile"));
PdfICCBased ib = new PdfICCBased(icc);
ib.remove(PdfName.ALTERNATE);
outi.put(PdfName.DESTOUTPUTPROFILE, writer.addToBody(ib)
.getIndirectReference());
writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS,
new PdfArray(outi));
PdfContentByte cb = writer.getDirectContent();
for (int c = 0; c < comps; ++c) {
img = TiffImage.getTiffImage(ra, c + 1);
if (img != null) {
document.setPageSize(PageSize.A4);
document.newPage();
img.setAbsolutePosition(0, 0);
img.scaleToFit(width, height);
cb.addImage(img);
logger.debug("Finished page " + (c + 1));
}
}
ra.close();
writer.createXmpMetadata();// pdfa
document.close();
} catch (Throwable e) {
// catch Throwable because we encountere a java.lang.InternalError
// cfr. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6503430
// probably better to move to later java version for poller
logger.error("Pdf not created", e);
}
}
示例7: generatePdf
import com.itextpdf.text.Image; //导入方法依赖的package包/类
private void generatePdf() {
try {
showProgressBar();
verifyStoragePermissions(this);
final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getResources().getString(R.string.folder_name) + File.separator + "eReceipt-" + transactionId + ".pdf";
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
Bitmap bitmap = Bitmap.createBitmap(
llall.getWidth(),
llall.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
llall.draw(c);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageInByte = stream.toByteArray();
Image myImage = Image.getInstance(imageInByte);
float documentWidth = document.getPageSize().getWidth();
float documentHeight = document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin();
myImage.scaleToFit(documentWidth, documentHeight);
myImage.setAlignment(Image.ALIGN_CENTER | Image.MIDDLE);
document.add(myImage);
document.close();
this.runOnUiThread(new Runnable() {
public void run() {
Intent email = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.fromFile(new File(path));
email.putExtra(Intent.EXTRA_STREAM, uri);
email.putExtra(Intent.EXTRA_SUBJECT, "eReceipt " + date);
email.setType("application/pdf");
email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(email);
}
});
hideProgressBar();
} catch (Exception e) {
Log.e(TAG, "Exception while tryig to share receipt info. Msg: " + e.getMessage());
}
}
示例8: addImageToPdf
import com.itextpdf.text.Image; //导入方法依赖的package包/类
/**
* The <code>addImageToPdf</code> method is used to add image to pdf and make it searchable by adding image text in invisible mode
* w.r.t parameter 'isPdfSearchable' passed.
*
* @param pdfWriter {@link PdfWriter} writer of pdf in which image has to be added
* @param htmlUrl {@link HocrPage} corresponding html file for fetching text and coordinates
* @param imageUrl {@link String} url of image to be added in pdf
* @param isPdfSearchable true for searchable pdf else otherwise
* @param widthOfLine
*/
private void addImageToPdf(PdfWriter pdfWriter, HocrPage hocrPage, String imageUrl, boolean isPdfSearchable, final int widthOfLine) {
if (null != pdfWriter && null != imageUrl && imageUrl.length() > 0) {
try {
LOGGER.info("Adding image" + imageUrl + " to pdf using iText");
Image pageImage = Image.getInstance(imageUrl);
float dotsPerPointX = pageImage.getDpiX() / PDF_RESOLUTION;
float dotsPerPointY = pageImage.getDpiY() / PDF_RESOLUTION;
PdfContentByte pdfContentByte = pdfWriter.getDirectContent();
pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
pageImage.setAbsolutePosition(0, 0);
// Add image to pdf
pdfWriter.getDirectContentUnder().addImage(pageImage);
pdfWriter.getDirectContentUnder().add(pdfContentByte);
// If pdf is to be made searchable
if (isPdfSearchable) {
LOGGER.info("Adding invisible text for image: " + imageUrl);
float pageImagePixelHeight = pageImage.getHeight();
Font defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);
// Fetch text and coordinates for image to be added
Map<String, int[]> textCoordinatesMap = getTextWithCoordinatesMap(hocrPage, widthOfLine);
Set<String> ketSet = textCoordinatesMap.keySet();
// Add text at specific location
for (String key : ketSet) {
int[] coordinates = textCoordinatesMap.get(key);
float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;
pdfContentByte.beginText();
// To make text added as invisible
pdfContentByte.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
pdfContentByte.setLineWidth(Math.round(bboxWidthPt));
// Ceil is used so that minimum font of any text is 1
// For exception of unbalanced beginText() and endText()
if (bboxHeightPt > 0.0) {
pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), (float) Math.ceil(bboxHeightPt));
} else {
pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), 1);
}
float xCoordinate = (float) (coordinates[0] / dotsPerPointX);
float yCoordinate = (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY);
pdfContentByte.moveText(xCoordinate, yCoordinate);
pdfContentByte.showText(key);
pdfContentByte.endText();
}
}
pdfContentByte.closePath();
} catch (BadElementException badElementException) {
LOGGER
.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
+ badElementException.toString());
} catch (DocumentException documentException) {
LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + documentException.toString());
} catch (MalformedURLException malformedURLException) {
LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: "
+ malformedURLException.toString());
} catch (IOException ioException) {
LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + ioException.toString());
}
}
}
示例9: doInBackground
import com.itextpdf.text.Image; //导入方法依赖的package包/类
@Override
protected Exception doInBackground(String... photos) {
try {
// Get output Directory
// Create the PDF and set some metadata
Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN);
Resources resources = mContext.getResources();
document.addTitle(mFilename);
document.addAuthor(resources.getString(R.string.app_name));
document.addSubject(resources.getString(R.string.file_subject));
// Open the file that we will write the pdf to.
java.io.File fileContent = new java.io.File(ImageUtils.getAlbumStorageDir(MainActivity.ALBUM_NAME) + mFilename);
OutputStream outputStream = new FileOutputStream(fileContent);
PdfWriter.getInstance(document, outputStream);
document.open();
// Get the document's size
Rectangle pageSize = document.getPageSize();
float pageWidth = pageSize.getWidth() - (document.leftMargin() + document.rightMargin());
float pageHeight = pageSize.getHeight();
//Loop through images and add them to the document
for (String path : photos) {
Image image = Image.getInstance(path);
image.scaleToFit(pageWidth, pageHeight);
document.add(image);
document.newPage();
}
// Cleanup
document.close();
outputStream.close();
// Upload time!
FileContent mediaContent = new FileContent("application/pdf", fileContent);
File body = new File();
if (mFolder != null)
body.setParents(Arrays.asList(new ParentReference().setId(mFolder.getId())));
body.setTitle(mFilename);
body.setDescription(resources.getString(R.string.file_subject));
body.setMimeType("application/pdf");
Drive.Files.Insert insert = mService.files().insert(body, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
uploader.setProgressListener(new FileProgressListener());
File file = insert.execute();
Log.d("C2P", "File Id: " + file.getId());
/* Database Code */
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
//file.getFileSize().toString()
String parentFolder = mFolder != null ? mFolder.getId() : "root";
Long size = file.getFileSize();
String fileSizeString = humanReadableByteCount(size);
Upload upload = new Upload(-1, mFilename, mFolderPath, fileSizeString, parentFolder, format.format(date), mService.about().get().execute().getUser().getEmailAddress());
UploadDataAdapter mUploadDataAdapter = new UploadDataAdapter(mContext);
mUploadDataAdapter.open();
mUploadDataAdapter.addUpload(upload);
mUploadDataAdapter.close();
} catch (Exception e) {
Log.d("C2P", "ERROR", e);
return e;
}
return null;
}
示例10: createPdf
import com.itextpdf.text.Image; //导入方法依赖的package包/类
public void createPdf(String filename) throws DocumentException, IOException {
Document document = new Document(PageSize.LETTER);
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
// step 4 - add content into document
String[] imageNames = { "35_Cal_Crutchlow.jpg", "38_Bradley_Smith.jpg", "46_Valentino_Rossi.jpg",
"99_Jorge_Lorenzo.jpg" };
for (int i = 0; i < 4; i++) {
// TODO: 1. Add image into Chunk
Image image = Image.getInstance("resources/img/" + imageNames[i]);
image.scaleToFit(500, 500);
Chunk imageChunk = new Chunk(image, 0, 0, true);
Phrase phrase = new Phrase(imageNames[i]);
Paragraph paragraph = new Paragraph();
paragraph.add(imageChunk);
paragraph.add(Chunk.NEWLINE);
paragraph.add(phrase);
// TODO: 2. Ask iText to keep a paragraph together
paragraph.setKeepTogether(true);
paragraph.setSpacingAfter(12);
document.add(paragraph);
}
document.close();
}