Insert Image as New Layer in Photoshop - photoshop

I want create new layer with image in it. I didn't find anything useful or correct answer for this question.
What I'm doing now is:
var oldActive = app.activeDocument;
app.load(new File(path)); //load it into documents
var tempDoc = app.activeDocument;
// backFile.resizeImage(width, height); //resize image into given size i.e 640x480
tempDoc.selection.selectAll();
tempDoc.selection.copy(); //copy image into clipboard
tempDoc.close(SaveOptions.DONOTSAVECHANGES); //close image without saving changes
oldActive.paste(); //paste selection into your document
Code above opens new document/tab and doing simple logic, then closes new document and brings me back to the old one and pastes image what I need.
I don't like this approach because user can see how documents blinking/opens/closes.
I'm looking for a simple way which allows insert image into current active Document without opening new ones.

Ok guys. So this is correct way to paste image by path into current activeDocument without opening new ones:
var sourceFile= new File(path);
var idPlc = charIDToTypeID( "Plc " );
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
desc3.putPath( idnull, sourceFile);
var idFTcs = charIDToTypeID( "FTcs" );
var idQCSt = charIDToTypeID( "QCSt" );
var idQcsa = charIDToTypeID( "Qcsa" );
desc3.putEnumerated( idFTcs, idQCSt, idQcsa );
executeAction( idPlc, desc3, DialogModes.NO );

Related

Photoshop script how to add image to a layer

How can I grab an image by its location on my local machine and insert it into a layer with extendscript?
var doc = app.documents.add();
var layer = doc.artLayers.add();
var img = new File('~/Desktop/tanks.png');
layer.image = img; //I want to add the image to this layer
All I can seem to do is open the image as a background which creates a new photoshop doc in the process;
var opened = open(img);
But what I would like to achieve is to open multiple images into the same doc as multiple layers. Can this be done?
Open each of the images you want to consolidate using the open method you found. Then cycle through the open document and use the duplicate method on the art layer object to copy all the layers to a single target document. See the code snippet below for copying a single layer image to a new doc.
//copy the layer into the target document
app.activeDocument = pSourceDocument;
pSourceDocument.artLayers[0].duplicate(pTargetDocument);
I found a very useful script for doing this here https://forums.adobe.com/message/3946944#3946944
I took the piece of this script and it worked for me. First of all, you need to convert the layer which contents you want to replace with the image to a Smart Object (in other case contents of the layer can't be replaced by scripts). To do so, open the file you want to modificate in Photoshop, select the layer, click Layer > Smart Objects > Group into New Smart Object. Now this layer is a Smart Object.
Then create a script with the following code:
var replacementFile = new File("X:/file.jpg");
var theLayer = app.documents[0].artLayers.getByName("targetLayer");
theLayer = replaceContents(replacementFile);
////// replace contents //////
function replaceContents (newFile) {
// =======================================================
var idplacedLayerReplaceContents = stringIDToTypeID( "placedLayerReplaceContents" );
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
desc3.putPath( idnull, new File( newFile ) );
var idPgNm = charIDToTypeID( "PgNm" );
desc3.putInteger( idPgNm, 1 );
executeAction( idplacedLayerReplaceContents, desc3, DialogModes.NO );
return app.activeDocument.activeLayer
};

cannot load image in isolated storage when creating IconicTile

I'm trying to create IconicTile using image saved on isolated storage.
At first, I saved image to isolated storage.
// bitmap is Stream of image source (e.g. from PhotoChooserTask)
var wbmp = new WriteableBitmap(bitmap);
var file = "Shared/ShellContent/IconicTile.png";
// when file exists, delete it
if (storage.FileExists(file))
{
storage.DeleteFile(file);
}
using (var isoFileStream = new IsolatedStorageFileStream(file, FileMode.Create, storage))
{
// use ToolStackPNGWriterExtensions
wbmp.WritePNG(isoFileStream);
}
And I have confirmed PNG file is successfully created using Isostorage Explorer Tools.
Then I try to create IconicTile.
var initialData = new IconicTileData
{
BackgroundColor = SelectedColor,
IconImage = new Uri("isostore:/Shared/ShellContent/IconicTile.png", UriKind.Absolute),
Title = tbTitle.Text,
WideContent1 = tbWideContent1.Text,
WideContent2 = tbWideContent2.Text,
WideContent3 = tbWideContent3.Text
};
var uri = string.Format("/SecondaryPage.xaml");
var TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(uri));
if (TileToFind == null)
ShellTile.Create(new Uri(uri, UriKind.Relative), initialData, true);
else
TileToFind.Update(initialData);
But image in the created tile are white.
(I'd like to attach image but my reputation is too low. Sorry.)
I tried not only PNG format but also JPG format, but neither doesn't work.
Is there anyway to create IconicTile using image on IsolatedStorage?
The iconic tile format expects a transparent background, based on your comment at the first line (PhotoChooserTask), I suspect you're using some type of image with no transparency.

How to exactly position an Image inside an existing PDF page using PDFBox?

I am able to insert an Image inside an existing pdf document, but the problem is,
The image is placed at the bottom of the page
The page becomes white with the newly added text showing on it.
I am using following code.
List<PDPage> pages = pdDoc.getDocumentCatalog().getAllPages();
if(pages.size() > 0){
PDJpeg img = new PDJpeg(pdDoc, in);
PDPageContentStream stream = new PDPageContentStream(pdDoc,pages.get(0));
stream.drawImage(img, 60, 60);
stream.close();
}
I want the image on the first page.
PDFBox is a low-level library to work with PDF files. You are responsible for more high-level features. So in this example, you are placing your image at (60, 60) starting from lower-left corner of your document. That is what stream.drawImage(img, 60, 60); does.
If you want to move your image somewhere else, you have to calculate and provide the wanted location (perhaps from dimensions obtained with page.findCropBox(), or manually input your location).
As for the text, PDF document elements are absolutely positioned. There are no low-level capabilities for re-flowing text, floating or something similar. If you write your text on top of your image, it will be written on top of your image.
Finally, for your page becoming white -- you are creating a new content stream and so overwriting the original one for your page. You should be appending to the already available stream.
The relevant line is:
PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0));
What you should do is call it like this:
PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0), true, true);
The first true is whether to append content, and the final true (not critical here) is whether to compress the stream.
Take a look at AddImageToPDF sample available from PDFBox sources.
Try this
doc = PDDocument.load( inputFileName );
PDXObjectImage ximage = null;
ximage = new PDJpeg(doc, new FileInputStream( image )
PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get(0);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
contentStream.drawImage( ximage, 425, 675 );
contentStream.close();
This prints the image in first page. If u want to print in all pages just put on a for loop with a condition of number of pages as the limit.
This worked for me well!
So late answer but this is for who works on it in 2020 with Kotlin: drawImage() is getting float values inside itself so try this:
val file = File(getPdfFile(FILE_NAME))
val document = PDDocument.load(file)
val page = document.getPage(0)
val contentStream: PDPageContentStream
contentStream = PDPageContentStream(document, page, true, true)
// Define a content stream for adding to the PDF
val bitmap: Bitmap? = ImageSaver(this).setFileName("sign.png").setDirectoryName("signature").load()
val mediaBox: PDRectangle = page.mediaBox
val ximage: PDImageXObject = JPEGFactory.createFromImage(document, bitmap)
contentStream.drawImage(ximage, mediaBox.width - 4 * 65, 26f)
// Make sure that the content stream is closed:
contentStream.close()
// Save the final pdf document to a file
pdfSaveLocation = "$directoryPDF/$UPDATED_FILE_NAME"
val pathSave = pdfSaveLocation
document.save(pathSave)
document.close()
I am creating a new PDF and running below code in a loop - to add one image per page and below co-ordinates and height and width values work well for me.
where out is BufferedImage reference variable
PDPage page = new PDPage();
outputdocument.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(outputdocument, page, AppendMode.APPEND, true);
PDImageXObject pdImageXObject = JPEGFactory.createFromImage(outputdocument, out);
contentStream.drawImage(pdImageXObject, 5, 2, 600, 750);
contentStream.close();
This link gives you details about Class PrintImageLocations.
This PrintImageLocations will give you the x and y coordinates of the images.
Usage: java org.apache.pdfbox.examples.util.PrintImageLocations input-pdf

chart location of pie chart in iText pdf in java

I'm creating a pie chart using jFreechart and add the chart in pdf created in iText. The problem is chart is always added at the bottom of the page and not after the last line.
A sample code for regenrating the error is:
Document document = new Document();
PdfWriter writer;
File file = new File("c:/myPdf.pdf");
writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
try {
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("OPT 1", 10);
pieDataset.setValue("OPT 2", 0);
pieDataset.setValue("OPT 3", 17);
pieDataset.setValue("OPT 4", 11);
JFreeChart chart = ChartFactory.createPieChart3D("Option click count",
pieDataset, true, false, false);
final PiePlot3D plot = (PiePlot3D) chart.getPlot();
plot.setNoDataMessage("No data to display");
chart.setTitle(new TextTitle("Option Click Count", new Font("Times New Roman", Font.PLAIN, 14)));
PdfContentByte pdfContentByte = writer.getDirectContent();
PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(225,225);
Graphics2D graphicsChart = pdfTemplateChartHolder.createGraphics(225,225,new DefaultFontMapper());
Rectangle2D chartRegion =new Rectangle2D.Double(0,0,225,225);
chart.draw(graphicsChart,chartRegion);
graphicsChart.dispose();
pdfContentByte.addTemplate(pdfTemplateChartHolder,0,0);
} catch (Exception e) {
e.printStackTrace();
}
document.close();
Here the options are fetched from database so not sure on the count of the option. I want to show chart right to the table. How can I do this?
You are adding the chart as a template, and per definition they are added with absolute coordinates.
If you are using floating elements, as I assume you are, you can use com.lowagie.itext.Image (version 2.1), and in newer versions com.itextpdf.text.Image.
You can use the Image class to create the template, and add it as a Element:
See here (iText API).
PdfContentByte pdfContentByte = writer.getDirectContent();
PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(225,225);
Graphics2D graphicsChart = pdfTemplateChartHolder.createGraphics(225,225,new DefaultFontMapper());
Rectangle2D chartRegion = new Rectangle2D.Double(0,0,225,225);
chart.draw(graphicsChart,chartRegion);
graphicsChart.dispose();
Image chartImage = Image.getInstance(pdfTemplateChartHolder);
document.add(chartImage);
The code example above shows the gist of it. You should as often as possible use Element objects such as Image if you don't want to handle heights and positions absolutely.

How to Add a link to a PDF with ColdFusion and iText

I used this technique to insert an image
Adding a dynamic image to a PDF using ColdFusion and iText
Now, I need to insert a link to a external URL at X/Y and text inside with itext and ColdFusion.
Can someone help me do this?
Thanks.
Here is rough example that works with CF9. There are probably more elegant methods, but this should give you the basic idea.
Note - IIRC CF8 uses an earlier version of iText (1.4). CF9 uses 2.1.0. So I am relatively certain it will not run "as is" with CF8. If needed, you can use the JavaLoader.cfc to run a later version.
Update: Modified to show one way of defining a specific font, size and color. The correct settings will vary depending on your system, desired font, encoding, etcetera.
<cfscript>
inputPath = "c:\sourceFile.pdf";
outputPath = "c:\sourceFileWithLink.pdf";
try {
// initialize objects
pdfReader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( inputPath );
outStream = createObject("java", "java.io.FileOutputStream").init( outputPath );
pdfStamper = createObject("java", "com.lowagie.text.pdf.PdfStamper").init( pdfReader, outStream );
// create a chunk with a link to www.google.com
chunk = createObject("java", "com.lowagie.text.Chunk").init("Go To Google");
chunk.setAnchor("http://www.google.com");
//////////////////////////////////////////
// Define embedded font
BaseFont = createObject("java", "com.lowagie.text.pdf.BaseFont");
Font = createObject("java", "com.lowagie.text.Font");
bf = BaseFont.createFont("c:/windows/fonts/Framd.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
// Create the main font object (size 14)
Color = createObject("java", "java.awt.Color");
textFont = Font.init(bf, 14, Font.UNDERLINE, Color.RED);
// Apply the font to the chunk text
chunk.setFont( textFont );
//////////////////////////////////////////
// prepare to write the link onto the *first* page only
cb = pdfStamper.getOverContent(1); // first page
ct = createObject("java", "com.lowagie.text.pdf.ColumnText").init(cb);
ct.addElement( chunk );
// position towards bottom right of page
page = pdfReader.getPageSize(1);
llx = page.getRight()-200;
lly = page.getBottom();
urx = page.getRight();
ury = page.getBottom() + 36;
// initialize column dimensions
ct.setSimpleColumn(llx, lly, urx, ury);
// write the text
ct.go();
WriteOutput("Finished!");
}
finally
{
// cleanup
if (IsDefined("pdfStamper")) {
pdfStamper.close();
}
if (IsDefined("outStream")) {
outStream.close();
}
}
</cfscript>