Update text layer in psd file in C# - c#

I want to update a specific text layer of psd file (always the same (find with his name)) in C#.
I searched and tested a lot of libraries which didn't working.
Recently, I found this library on GitHub : https://github.com/bizzehdee/System.Drawing.PSD
I downloaded sources, try it and in C#, I can access to my specifid layer, but, I can't update it.
In Layer class, there are differents attributs but I don't control them.
I wan't to know if there is anybody who can test it and help me to understand the library.
I asked the author but his last action is in last year...
I hope you can help me !
Thank you very much.

You can try Aspose.PSD. It supports simple text layer editing and editing text layer by portions: https://docs.aspose.com/display/psdnet/Working+With+Text+Layers
// Load a PSD file as an image and cast it into PsdImage
using (PsdImage psdImage = (PsdImage)Image.Load(dataDir + "layers.psd"))
{
foreach (var layer in psdImage.Layers)
{
if (layer is TextLayer)
{
TextLayer textLayer = layer as TextLayer;
textLayer.UpdateText("test update", new Point(0, 0), 15.0f, Color.Purple);
}
}
psdImage.Save(dataDir + "UpdateTextLayerInPSDFile_out.psd");
}
Example with Text Portions:
string sourceFile = dataDir + "text212.psd";
string outputFile = dataDir + "Output_text212.psd";
using (var img = (PsdImage)Image.Load(sourceFile))
{
TextLayer textLayer = (TextLayer)img.Layers[1];
IText textData = textLayer.TextData;
ITextStyle defaultStyle = textData.ProducePortion().Style;
ITextParagraph defaultParagraph = textData.ProducePortion().Paragraph;
defaultStyle.FillColor = Color.DimGray;
defaultStyle.FontSize = 51;
textData.Items[1].Style.Strikethrough = true;
ITextPortion[] newPortions = textData.ProducePortions(new string[]
{
"E=mc", "2\r", "Bold", "Italic\r",
"Lowercasetext"
},
defaultStyle,
defaultParagraph);
newPortions[0].Style.Underline = true; // edit text style "E=mc"
newPortions[1].Style.FontBaseline = FontBaseline.Superscript; // edit text style "2\r"
newPortions[2].Style.FauxBold = true; // edit text style "Bold"
newPortions[3].Style.FauxItalic = true; // edit text style "Italic\r"
newPortions[3].Style.BaselineShift = -25; // edit text style "Italic\r"
newPortions[4].Style.FontCaps = FontCaps.SmallCaps; // edit text style "Lowercasetext"
foreach (var newPortion in newPortions)
{
textData.AddPortion(newPortion);
}
textData.UpdateLayerData();
img.Save(outputFile);
}

I dont use Aspose because it's not free for use.
All you need is AdobeStandard.COM-component.
Photoshop.Application app = new Photoshop.Application();
Photoshop.Document doc = app.Open(#"test.psd");
for(int i = 1; i <= doc.ArtLayers.Count; i++)
{
string name = doc.ArtLayers[i].Name;
if (name.Equals("Title1"))
{
doc.ArtLayers[i].TextItem.Contents = "Hello World";
}
}

Related

Detect if a users Anti-Virus or Browser is blocking marketing tracking code like Facebook FBQ?

Is there a way you can detect in C# if a browser is blocking external marketing
tracking information like fbq?
In JQuery you can use typeof fbq !== 'undefined' to detect if the Facebook Pixel tracking code is blocked, For example:
if(typeof fbq !== 'undefined'){
fbq('track', 'ViewContent', {
value: FacebookPriceIncVat,
currency: FacebookInitiateCheckoutCurrency,
content_ids: FacebookSKUView,
content_type: 'product',
});
}
I have one module in which the Facebook Tracking code can only be generated on the back-end. Is there a way you can detect if fbq exist using perhaps ajax that changes a bool or some other way to detect if something is blocking links in your browser like a plugin of some sort?
The code below should not execute if fbq is not present.
if (FacebookPixelID != null)
{
EndUserFirstName = SessionManager.CurrentUserInfo.FirstName;
EndUserLastName = SessionManager.CurrentUserInfo.LastName;
EndUserEmail = SessionManager.CurrentUserInfo.UserName;
FacebookInitializationCodeID = FacebookPixelID;
string FacebookPixelResult = string.Empty;
using (var FBPxl = new StringWriter())
using (var FBCodescript = new HtmlTextWriter(FBPxl))
{
FBCodescript.AddAttribute(Attr.Type, "text/javascript");
FBCodescript.RenderBeginTag(Tag.Script);
//load ecommerce plugin
FBCodescript.WriteLine("!function(f,b,e,v,n,t,s){if (f.fbq) return; n = f.fbq = function(){n.callMethod?n.callMethod.apply(n, arguments):n.queue.push(arguments)};");
FBCodescript.WriteLine("if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0';");
FBCodescript.WriteLine("n.queue =[]; t = b.createElement(e); t.async = !0;");
FBCodescript.WriteLine("t.src = v; s = b.getElementsByTagName(e)[0];");
FBCodescript.WriteLine("s.parentNode.insertBefore(t, s)}");
FBCodescript.WriteLine("(window, document,'script','https://connect.facebook.net/en_US/fbevents.js');");
FBCodescript.WriteLine($"fbq('init', '{FacebookInitializationCodeID}', {{ em: '{EndUserEmail}', fn: '{EndUserFirstName}', ln: '{EndUserLastName}',}});");
FBCodescript.WriteLine("fbq('track', 'PageView');");
FBCodescript.RenderEndTag();
FBCodescript.WriteLine($"<noscript><img height='1' width='1' style='display:none' src='https://www.facebook.com/tr?id={FacebookInitializationCodeID}&ev=PageView&noscript=1'/></noscript>");
FacebookPixelResult = FBCodescript.InnerWriter.ToString();
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFacebookPixelInitialization", FacebookPixelResult, false);
//Facebook Pixels Purchase Code
string FacebookPixelPurchase = string.Empty;
if (RevenueCurrency != null)
{
FBPurchaseCurrency = RevenueCurrency;
}
else
{
FBPurchaseCurrency = "ZAR";
}
using (var FBPxlPurchase = new StringWriter())
using (var FBCodescriptPurchase = new HtmlTextWriter(FBPxlPurchase))
{
FBCodescriptPurchase.AddAttribute(Attr.Type, "text/javascript");
FBCodescriptPurchase.RenderBeginTag(Tag.Script);
//Write Facebook Pixel Purchase Event code
FBCodescriptPurchase.WriteLine("fbq('track', 'Purchase', {");
FBCodescriptPurchase.WriteLine($"value: {trans.Revenue},");
FBCodescriptPurchase.WriteLine($"currency: '{FBPurchaseCurrency}',");
FBCodescriptPurchase.WriteLine($"content_ids: '{string.Join(",", trans.LineItems.Select(l => l.SKU).ToArray())}',");
FBCodescriptPurchase.WriteLine("content_type: 'product',");
FBCodescriptPurchase.WriteLine($"contents: [");
var PurchaseCounter = 1;
foreach (var lineitem in trans.LineItems)
{
FBCodescriptPurchase.WriteLine("{");
FBCodescriptPurchase.WriteLine($"id: '{lineitem.SKU}',");
FBCodescriptPurchase.WriteLine($"quantity: {lineitem.Quantity},");
FBCodescriptPurchase.WriteLine($"item_price: {lineitem.UnitPrice}");
FBCodescriptPurchase.WriteLine("}");
if (PurchaseCounter != trans.LineItems.Count) FBCodescriptPurchase.WriteLine(",");
PurchaseCounter++;
}
FBCodescriptPurchase.WriteLine("]");
FBCodescriptPurchase.WriteLine("});");
FBCodescriptPurchase.RenderEndTag();
FacebookPixelPurchase = FBCodescriptPurchase.InnerWriter.ToString();
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFacebookPixelPurchase", FacebookPixelPurchase, false);
}
}
I think it is actually easy to fix this.
Don't know why I did not think of this.
I can just add the if statement in the C# code.

Paragraph not changing to desired format in ppt with openxml

I'm trying to edit a paragraph in pptx through changing its text, font size, font style and alignment.
This is what i have done so far:
**this is the method im using to call the update paragraph**
public static void Main(string[] args)
{
using (PresentationDocument presentationDocument = PresentationDocument.Open("ppturl", true))
{
// Get the presentation part of the presentation document.
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation part and presentation exist.
if (presentationPart != null && presentationPart.Presentation != null)
{
// Get the Presentation object from the presentation part.
Presentation presentation = presentationPart.Presentation;
// Verify that the slide ID list exists.
if (presentation.SlideIdList != null)
{
SlideId sourceSlide = presentation.SlideIdList.ChildElements[0] as SlideId;
SlidePart slidePart = presentationPart.GetPartById(sourceSlide.RelationshipId) as SlidePart;
updateParagraph(slidePart);
}
}
}
Console.ReadLine();
CreateHostBuilder(args).Build().Run();
}
**Here im extracting the title in the slide because this is what i need.**
public static void updateParagraph(SlidePart slidePart)
{
if (slidePart == null)
{
throw new ArgumentNullException("presentationDocument");
}
if (slidePart.Slide != null)
{
// Find all the title shapes.
var shapes = from shape in slidePart.Slide.Descendants<Shape>()
where IsTitleShape(shape)
select shape;
foreach (P.Shape shape in shapes)
{
D.Paragraph paragraph = shape.TextBody.Elements<D.Paragraph>().FirstOrDefault();
shape.TextBody.RemoveAllChildren<D.Paragraph>();
AddNewParagraph(shape, "This is a new Slide");
}
}
}
**This is where i am trying to add a new paragraph with specific style**
public static void AddNewParagraph(this P.Shape shape, string NewText)
{
D.Paragraph p = new D.Paragraph();
P.TextBody docBody = shape.TextBody;
Justification justification1 = new Justification() { Val = JustificationValues.Center };
p.ParagraphProperties=new D.ParagraphProperties(justification1);
D.Run run = new D.Run(new D.Text(NewText));
D.RunProperties runProp = new D.RunProperties() { Language = "en-US", FontSize = 9, Dirty = false };
run.AppendChild(runProp);
D.Text newText = new D.Text(NewText);
run.AppendChild(newText);
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine(runProp.FontSize.ToString());
Console.WriteLine("--------------------------------------------------------------");
p.Append(run);
docBody.Append(p);
}
This is giving me an error whenever im trying to open the pptx "repair pptx error".
Can someone please provide a clear solution specific to pptx and not doc.?
Thankful..
You can try using Aspose.Slides for .NET. The following code example shows you how to change some paragraph properties with this library:
using (var presentation = new Presentation("example.pptx"))
{
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
var firstPortion = firstParagraph.Portions[0];
firstPortion.Text = "New text.";
firstPortion.PortionFormat.FontHeight = 24;
firstPortion.PortionFormat.FontBold = NullableBool.True;
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
presentation.Save("example.pptx", SaveFormat.Pptx);
}
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to change the paragraph settings using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var fileName = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var portionIndex = 1;
var firstPortion = slidesApi.GetPortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex);
firstPortion.Text = "New text.";
firstPortion.FontHeight = 24;
firstPortion.FontBold = Portion.FontBoldEnum.True;
slidesApi.UpdatePortion(
fileName, slideIndex, shapeIndex, paragraphIndex, portionIndex, firstPortion);
var firstParagraph = slidesApi.GetParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex);
firstParagraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
fileName, slideIndex, shapeIndex, paragraphIndex, firstParagraph);
I work as a Support Developer at Aspose.

how to get image from pdf using pdfbox in c# .net

how to get image from pdf using pdfbox in c# .net.
All the answer about this question are posted in java language.
No one post correct answer in c# language in what I've seen.
I'm tried the java code in c# but some methods are not working in c#.
I want to extract image from pdf file using pdfbox in c# .net
Finally I got the answer.
Extend the class in your class PDFStreamEngine
Example:
public class ImageExtraction : PDFStreamEngine
{
int i=1;
public void GetImageFromPDF(string fileName)
{
PDDocument pDDocument = PDDocument.load(new java.io.File(fileName));
PDPage page = new PDPage();
page = pDDocument.getPages().get(0);
ImageExtraction obj = new ImageExtraction();
processPage(page);
}
protected override void processOperator(Operator #operator, java.util.List operands)
{
string operation = #operator.getName();
if (operation == "Do")
{
PDDocument pDDocument = new PDDocument();
org.apache.pdfbox.cos.COSName objectName = (org.apache.pdfbox.cos.COSName)operands.get(0);
org.apache.pdfbox.pdmodel.graphics.PDXObject xobject = getResources().getXObject(objectName);
org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject pDImageXObject = new org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject(pDDocument);
org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject pDFormXObject = new org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject(pDDocument);
if (xobject.GetType().IsAssignableFrom(pDImageXObject.GetType()))
{
org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject image = (org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject)xobject;
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
// same image to local
java.awt.image.BufferedImage bImage = new java.awt.image.BufferedImage(imageWidth,
imageHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB);
bImage = image.getImage();
javax.imageio.ImageIO.write(bImage, "PNG", new java.io.File(imageFolderPath + "image_" + i + ".png"));
i++;
Console.WriteLine("Image saved.");
}
else if (xobject.GetType().IsAssignableFrom(pDFormXObject.GetType()))
{
org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject form = (org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject)xobject;
showForm(form);
}
}
}
}
Looks like someone started a dotnet port of pdfbox.
https://github.com/UglyToad/PdfPig

Render a barcode in ASP.NET Web Form

i am trying to show the barcode in asp.net page. already download the zen barcode render with sample code. i tried the sample it is working fine with me. once i try in my code barcode label is showing empty. i checked with sample code and mine i did not find any difference , only data transfer is the different. this is what i tried.
<barcode:BarcodeLabel ID="BarcodeLabel1" runat="server" BarcodeEncoding="Code39NC" LabelVerticalAlign="Bottom" Text="12345"></barcode:BarcodeLabel>
if (!IsPostBack)
{
List<string> symbologyDataSource = new List<string>(
Enum.GetNames(typeof(BarcodeSymbology)));
symbologyDataSource.Remove("Unknown");
barcodeSymbology.DataSource = symbologyDataSource;
barcodeSymbology.DataBind();
}
this is the function
BarcodeSymbology symbology = BarcodeSymbology.Unknown;
if (barcodeSymbology.SelectedIndex != 0)
{
symbology = (BarcodeSymbology)1;
}
symbology = (BarcodeSymbology)1;
string text = hidID.Value.ToString();
string scaleText = "1";
int scale;
if (!int.TryParse(scaleText, out scale))
{
if (symbology == BarcodeSymbology.CodeQr)
{
scale = 3;
}
else
{
scale = 1;
}
}
else if (scale < 1)
{
scale = 1;
}
if (!string.IsNullOrEmpty(text) && symbology != BarcodeSymbology.Unknown)
{
barcodeRender.BarcodeEncoding = symbology;
barcodeRender.Scale = 1;
barcodeRender.Text = text;
}
symbology is set as Code39NC from the dropdown. scale is 1 and text is coming from other form the value is passing as well. still the bacodelable is showing only value not the barcode picture.
Here are two code samples using ZXing to create a (QR) barcode as both an image and as a base64 encoded string. Both of these options can be used with an <img /> tag to embed the barcode in the page.
This is not an ASP.NET control. It is a library that creates barcodes from text.
// First Text to QR Code as an image
public byte[] ToQRAsGif(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = this._h,
Width = this._w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
stream.Position = 0;
return stream.GetBuffer();
}
}
// From Text to QR Code as base64 string
public string ToQRAsBase64String(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = _h,
Width = _w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
return String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(stream.ToArray()));
}
}
Hope this helps! Happy coding.
UPDATE: Here is the link to their product page on codeplex: https://zxingnet.codeplex.com/

Displaying image in web application

i have problem with displaying image in my web app. It took photo from database, and should dispay in web app.
protected void btnShowPhoto_Click(object sender, EventArgs e)
{
string adresURL = #"~/Content";
string camPath = "";
string[] tab = new string[10];
CheckBox[] _boxes = new CheckBox[] { this.CheckBox1, this.CheckBox2, this.CheckBox3, this.CheckBox4, this.CheckBox5, this.CheckBox6, this.CheckBox7, this.CheckBox8 };
System.Web.UI.WebControls.Image[] _images = new System.Web.UI.WebControls.Image[] { this.Image1, this.Image2, this.Image3, this.Image4, this.Image5, this.Image6, this.Image7, this.Image8 };
Label[] _labels = new Label[] { this.lblCameraName1, this.lblCameraName2, this.lblCameraName3, this.lblCameraName4, this.lblCameraName5, this.lblCameraName6, this.lblCameraName7, this.lblCameraName8 };
System.Web.UI.HtmlControls.HtmlAnchor[] _linkscontrol = new System.Web.UI.HtmlControls.HtmlAnchor[] { this.imagelink1, this.imagelink2, this.imagelink3, this.imagelink4, this.imagelink5, this.imagelink6, this.imagelink7, this.imagelink8 };
for (int i = 0; i < 8; i++)
{
_images[i].Visible = false;
_labels[i].Visible = false;
_linkscontrol[i].HRef = "";
}
for (int i = 0; i < 8; i++)
{
if (_boxes[i].Checked)
{
camPath = null;
tab = null;
camPath = this.GridView2.Rows[i].Cells[0].Text;
tab = camPath.Split(new string[] { "StoredPhotos" }, StringSplitOptions.None);
//Virtual Path'a
camPath = adresURL + tab[1].Replace(#"\", "/");
_labels[i].Visible = true;
_labels[i].Text = this.GridView2.Rows[i].Cells[1].Text;
_linkscontrol[i].HRef = camPath;
_images[i].ImageUrl = camPath;
_images[i].Visible = true;
}
else
_images[i].Visible = false;
}
}
I have problem with my virtual path probably. CamPath(Virtual Path) becomes from : E:\Photo\StoredPhotos\20151010\000003819619_201512021335_1_C1, and finally looks: ~/20151010/000003819619_201512021335_1_C1
This path means nothing to a web browser:
~/20151010/000003819619_201512021335_1_C1
It doesn't know what to do with that ~ directory. That's a server-side concept, not a client-side concept. So your server-side code needs to resolve that to an actual path.
It could be as simple as just explicitly starting from the root of the server:
string adresURL = #"/Content";
So the resulting URL would start with /Content/..... and the browser would check for the image in that path.
But if the application isn't (or might not be) the root of the server domain then you'd need to either manually account for that or use a server-side helper of some sort. There are a variety of ways to go about that, for example:
_images[i].ImageUrl = System.Web.VirtualPathUtility.ToAbsolute(camPath);
The browser expect access to image via http protocol, if you want view the image you have 2 diffrerent way:
(simple) Create a virtual directory under iis that point to a phisical folder E:\Photo\StoredPhotos\ and called StoredPhotos, in _images[i].ImageUrl you may set the value /StoredPhotos/20151010/000003819619_201512021335_1_C1.jpg
(complex) Build a class that read the file on the disk and write it to the response (use IHttpHandler interface), add this handler to web.config and set _images[i].ImageUrl the value of 'NameOfHandler.aspx?20151010/000003819619_201512021335_1_C1

Categories

Resources